Java Reference
In-Depth Information
A much better approach that can be used to process the elements from a collection sequentially involves
something called an
iterator
.
It is worth noting at this point that Java also provides something called an enumerator. An
enumerator provides essentially the same capability as an iterator, but it is recommended in the Java
documentation that you should use an iterator in preference to an enumerator for collections.
In general an iterator is an object that you can use to retrieve all the objects in a collection one by one.
Someone dealing cards from a deck one by one is acting as an iterator for the card deck - without the
shuffle, of course.
In Java, an iterator is an interface that can be implemented by a collection class. Any collection object
can create an object of type
Iterator
that encapsulates references to all the objects in the original
collection in some sequence, and that can be accessed using the
Iterator
interface methods. In other
words an iterator provides an easy way to get at all the objects in a collection one at a time. The basic
mechanism for using an iterator in Java is illustrated below.
Collection object (set or list)
collection
Calling its
iterator()
method
creates an object that is an
iterator.
An iterator is for one time
use. To access the
objects from a collection
again, you just obtain
another iterator object.
Iterator
object
iterator
Each successive call of the
next()
method
for the iterator returns the next object
Collection
object1
object2
object3
object4
The
Iterator
interface in
java.util
declares just three methods:
Method
Description
next()
Returns an object as type
Object
starting with the first, and sets the
Iterator
object to return the next object on the next call of this method. If
there is no object to be returned the method throws a
NoSuchElementException
exception.
hasNext()
Returns
true
if there is a next object to be retrieved by a call to
next()
.