Iterator and the Enhanced For Statement
Byextending Iterable , Collection inheritsthatinterface's iterator() meth-
od, which makes it possible to iterate over a collection. iterator() returns an in-
stance of a class that implements the Iterator interface, whose generic type is ex-
pressed as Iterator<E> and which declares the following three methods:
• boolean hasNext() returnstruewhenthis Iterator instancehasmore
elements to return; otherwise, this method returns false.
• E next() returns the next element from the collection associated with
this Iterator instance, or throws
java.util.NoSuchElementException when there are no more ele-
ments to return.
• void remove() removes the last element returned by next() from the
collectionassociatedwiththis Iterator instance.Thismethodcanbecalled
onlyonceper next() call.Thebehaviorofan Iterator instanceisunspe-
inanywayotherthanbycalling remove() .Thismethodthrows Unsuppor-
tedOperationException when it is not supported by this Iterator ,
and IllegalStateException when remove() hasbeencalledwithout
a previous call to next() or when multiple remove() calls occur with no
intervening next() calls.
The following example shows you how to iterate over a collection after calling
iterator() to return an Iterator instance:
Collection<String> col = ... // This code does not compile
because of the “...”.
// Add elements to col.
Iterator iter = col.iterator();
The while loop repeatedly calls the iterator's hasNext() method to determine
whetherornotiterationshouldcontinue,and(ifitshouldcontinue)the next() method
to return the next element from the associated collection.
Because this idiom is commonly used, Java 5 introduced syntactic sugar to the for
statement to simplify iteration in terms of the idiom. This sugar makes this statement
following simplified equivalent of the previous example: