Java Reference
In-Depth Information
NEW YORK ATLANTA DALLAS MADISON
The program creates a concrete collection object using
ArrayList
(line 5) and adds four
strings into the list (lines 6-9). The program then obtains an iterator for the collection (line 11)
and uses the iterator to traverse all the strings in the list and displays the strings in uppercase
(lines 12-14).
Tip
You can simplify the code in lines 11-14 using a foreach loop without using an iterator,
as follows:
foreach loop
for
(String element: collection)
System.out.print(element.toUpperCase() +
" "
);
This loop is read as “for each element in the collection, do the following.” The foreach
loop can be used for arrays (see Section 7.2.7) as well as any instance of
Iterable
.
20.6
✓
✓
How do you obtain an iterator from a collection object?
Check
20.7
What method do you use to obtain an element in the collection from an iterator?
Point
20.8
Can you use a foreach loop to traverse the elements in any instance of
Collection
?
20.9
When using a foreach loop to traverse all elements in a collection, do you need to use
the
next()
or
hasNext()
methods in an iterator?
The
List
interface extends the
Collection
interface and defines a collection for
storing elements in a sequential order. To create a list, use one of its two concrete
classes:
ArrayList
or
LinkedList
.
Key
Point
We used
ArrayList
to test the methods in the
Collection
interface in the preceding
sections. Now we will examine
ArrayList
in more depth. We will also introduce another
useful list,
LinkedList
, in this section.
20.4.1 The Common Methods in the
List
Interface
ArrayList
and
LinkedList
are defined under the
List
interface. The
List
interface
extends
Collection
to define an ordered collection with duplicates allowed. The
List
interface adds position-oriented operations, as well as a new list iterator that enables the user
to traverse the list bidirectionally. The methods introduced in the
List
interface are shown
in Figure 20.3.
The
add(index, element)
method is used to insert an element at a specified index, and
the
addAll(index, collection)
method to insert a collection of elements at a specified
index. The
remove(index)
method is used to remove an element at the specified index from
the list. A new element can be set at the specified index using the
set(index, element)
method.
The
indexOf(element)
method is used to obtain the index of the specified element's
first occurrence in the list, and the
lastIndexOf(element)
method to obtain the index of
its last occurrence. A sublist can be obtained by using the
subList(fromIndex, toIndex)
method.
Search WWH ::
Custom Search