Name
Iterator<E>
Synopsis
This
interface defines methods for iterating, or enumerating, the elements
of a collection. It has been made generic in Java 5.0 and the type
variable E represents the type of the
elements in the collection. The hasNext( ) method
returns true if there are more elements to be
enumerated or false if all elements have already
been returned. The next( ) method returns the next
element. These two methods make it easy to loop through an iterator
with code such as the following:
for(Iterator i = c.iterator( ); i.hasNext( ); )
processObject(i.next( ));In Java 5.0, collections and other classes that can return an
Iterator implement the
java.lang.Iterable interface, which allows them to
be iterated much more simply with the for/in
looping statement.
The
Iterator interface is much like the
Enumeration interface. In Java 1.2,
Iterator is preferred over
Enumeration because it provides a well-defined way
to safely remove elements from a collection while the iteration is in
progress. The remove( ) method removes the object
most recently returned by next( ) from the
collection that is being iterated through. Note, however, that
support for remove( ) is optional; if an
Iterator does not support remove(
), it throws a
java.lang.UnsupportedOperationException when you
call it. While you are iterating through a collection, you are
allowed to modify the collection only by calling the remove(
) method of the Iterator. If the collection is modified in any other way while an ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access