Java Reference
In-Depth Information
15.7
Example.
We can use an iterator to display all the entries in a list. The following statements display
the strings in the list
nameList
, one per line:
Iterator<String> nameIterator =
new
SeparateIterator<String>(nameList);
while
(nameIterator.hasNext())
System.out.println(nameIterator.next());
The iterator
nameIterator
begins just before the first entry in the list. As long as
hasNext
returns
true,
next
returns the next entry in the list and advances the iterator. Thus, every entry in the list is
retrieved and displayed.
15.8
Example.
The interface
Iterator
provides an operation to remove an entry from a data collection.
This entry is the one returned by the last call to the method
next
. Thus, you must invoke
next
before you can call
remove
.
If
nameList
contains the strings
Andy
,
Brittany
, and
Chris
, and
nameIterator
is defined as in
the previous example,
nameIterator.next()
returns the string
Andy
and advances the iterator.
●
nameIterator.next()
returns the string
Brittany
and advances the iterator.
●
nameIterator.remove()
removes
Brittany
from the list.
●
nameIterator.next()
returns the string
Chris
and advances the iterator.
●
Figure 15-3 shows the list during the previous iteration.
FIGURE 15-3
The effect of the iterator methods
next
and
remove
on a list
Iterator cursor
Andy
Brittany
Chris
Andy
Brittany
Chris
next()
returns
Andy
and
advances the iterator
Andy
Brittany
Chris
next()
returns
Brittany
and
advances the iterator
Andy
Chris
remove()
removes
Brittany
from the list
Andy
Chris
next()
returns
Chris
and
advances the iterator