Java Reference
In-Depth Information
A list of integers in the array list:
[10, 1, 2, 30, 3, 1, 4]
Display the linked list forward:
green 10 red 1 2 30 3 1
Display the linked list backward:
1 3 30 2 1 red 10 green
A list can hold identical elements. Integer
1
is stored twice in the list (lines 6, 9).
ArrayList
and
LinkedList
operate similarly. The critical difference between them pertains to internal
implementation, which affects their performance.
ArrayList
is efficient for retrieving ele-
ments and
LinkedList
is efficient for inserting and removing elements at the beginning of
the list. Both have the same performance for inserting and removing elements in the middle
or at the end of the list.
The
get(i)
method is available for a linked list, but it is a time-consuming operation. Do
not use it to traverse all the elements in a list as shown in (a). Instead you should use an iterator
as shown in (b). Note that a foreach loop uses an iterator implicitly. You will know the reason
when you learn how to implement a linked list in Chapter 24.
for
(
int
i =
0
; i < list.size(); i++) {
process list.get(i);
}
for
(listElementType s: list) {
process s;
}
(a) Very inefficient
(b) Efficient
Tip
Java provides the static
asList
method for creating a list from a variable-length list of
arguments. Thus you can use the following code to create a list of strings and a list of
integers:
Arrays.asList(T... a)
method
List<String> list1 = Arrays.asList(
"red"
,
"green"
,
"blue"
);
List<Integer> list2 = Arrays.asList(
10
,
20
,
30
,
40
,
50
);
20.10
✓
✓
How do you add and remove elements from a list? How do you traverse a list in both
directions?
Check
Point
20.11
Suppose that
list1
is a list that contains the strings
red
,
yellow
, and
green
, and
that
list2
is another list that contains the strings
red
,
yellow
, and
blue
. Answer
the following questions:
a. What are
list1
and
list2
after executing
list1.addAll(list2)
?
b. What are
list1
and
list2
after executing
list1.add(list2)
?
c. What are
list1
and
list2
after executing
list1.removeAll(list2)
?
d. What are
list1
and
list2
after executing
list1.remove(list2)
?
e. What are
list1
and
list2
after executing
list1.retainAll(list2)
?
f. What is
list1
after executing
list1.clear()
?
20.12
What are the differences between
ArrayList
and
LinkedList
? Which list should
you use to insert and delete elements at the beginning of a list?
20.13
Are all the methods in
ArrayList
also in
LinkedList
? What methods are in
LinkedList
but not in
ArrayList
?
20.14
How do you create a list from an array of objects?
Search WWH ::
Custom Search