Java Reference
In-Depth Information
Iterator
An object that allows the efficient retrieval of the elements of a list in
sequential order.
Using an iterator, when we move from one element to the next, we don't have to
go back to the beginning of the list at each call and follow the links all the way from
the front of the list to the desired index. As we'll see in this chapter, iterators are cen-
tral to the Java Collections Framework. Every collection provides iterators to access
its elements. In other words, there's a familiar interface for examining the elements
of any collection.
An iterator object has the methods listed in Table 11.2. The methods
next
and
hasNext
should be familiar from the
Scanner
class that you have already studied,
and their behavior is similar here.
To get an iterator from most collections, such as an
ArrayList
or a
LinkedList
,
you call the method
iterator
on the list, which returns an object of type
Iterator
for examining that list's elements. (You don't use the
new
keyword.) Generally, a
variable named
list
storing elements of type
E
uses an iterator in the following way:
Iterator<E> itr = list.iterator();
while (itr.hasNext()) {
<do something with itr.next()>;
}
The example of removing strings that have even length from a collection can be
implemented much more efficiently using an iterator:
// removes all strings of even length from the given linked list
public static void removeEvenLength(LinkedList<String> list) {
Iterator<String> i = list.iterator();
while (i.hasNext()) {
String element = i.next();
if (element.length() % 2 == 0) {
i.remove();
}
}
}
Table 11.2
Methods of
Iterator
Objects
Method
Description
Returns
true
if there are more elements to be examined
hasNext()
Returns the next element from the list and advances the position of the
iterator by one
next()
Removes the element most recently returned by
next()
remove()
Search WWH ::
Custom Search