Java Reference
In-Depth Information
An Iterator provides just three methods, and two of these are use to iterate over a collection:
hasNext and next . Neither takes a parameter, but both have non-void return types, so they are used
in expressions. The way we usually use an Iterator can be described in pseudo-code as follows:
Iterator< ElementType > it = myCollection.iterator();
while(it.hasNext()) {
call to get the next element
do something with that element
In this code fragment, we first use the iterator method of the ArrayList class to obtain an
Iterator object. Note that Iterator is also a generic type, so we parameterize it with the type
of the elements in the collection we are iterating over. Then we use that Iterator to repeatedly
check whether there are any more elements, it.hasNext (), and to get the next element, it.
next (). One important point to note is that it is the Iterator object that we ask to return the
next item, and not the collection object. Indeed, we tend not to refer directly to the collection at
all in the body of the loop; all interaction with the collection is done via the Iterator .
Using an Iterator , we can write a method to list the tracks, as shown in Code 4.8. In effect,
the Iterator starts at the beginning of the collection and progressively works its way through,
one object at a time, each time we call its next method.
Code 4.8
Using an Iterator
to list the tracks
* List all the tracks.
public void listAllTracks()
Iterator<Track> it = tracks.iterator();
while (it.hasNext()) {
Track t =;
Take some time to compare this version to the one using a for-each loop in Code 4.7 and the
two versions of listAllFiles shown in Code 4.3 and Code 4.5. A particular point to note
about the latest version is that we use a while loop, but we do not need to take care of the index
variable. This is because the Iterator keeps track of how far it has gotten through the collec-
tion, so that it knows both whether there are any more items left ( hasNext ) and which one to
return ( next ) if there is another.
One of the keys to understanding how Iterator works is that the call to next causes the
Iterator to return the next item in the collection and then move past that item . Therefore,
successive calls to next on an Iterator will always return distinct items; you cannot go back
to the previous item once next has been called. Eventually, the Iterator reaches the end
of the collection and then returns false from a call to hasNext . Once hasNext has returned
false , it would be an error to try to call next on that particular Iterator object—in effect, the
Iterator object has been “used up” and has no further use.
Search WWH ::

Custom Search