Java Reference
In-Depth Information
16.3
Iterators
The White Rabbit put on his spectacles. “Where shall I begin, please
your Majesty?” he asked.
“Begin at the beginning,” the King said, very gravely, “And go on till you
come to the end: then stop.”
LEWIS CARROLL,
Alice in Wonderland
iterator
An
iterator
is an object that is used with a collection to provide sequential access to
the elements in the collection. In this section, we discuss iterators in general and itera-
tors in the Java collection framework in particular.
The Iterator Concept
In the next subsection, we will discuss the Java
Iterator
interface, but before that, let's
consider the intuitive idea of an iterator. An iterator is something that allows you to
examine and possibly modify the elements in a collection in some sequential order. So,
an iterator imposes an order on the elements of a collection even if the collection, such
as the class
HashSet<T>
, does not impose any order on the elements it contains.
Something that is not an object—and thus not, strictly speaking, a Java
Iterator
—
but that satisfies the intuitive idea of an
iterator
is an
int
variable
i
used with an array
a
. This iterator
i
can be made to start out at the first array as follows:
i = 0;
The iterator can give you the current element; the current element is simply
a[i]
. The
iterator can go to the next element and give you the next element as follows:
i++;
“Gives you a[i]”
The concept of an iterator is simple but powerful enough to be used frequently.
The
Iterator<T>
IIInterface
Java formalizes the concept of an iterator with the
Iterator<T>
generic interface. Any
object of any class that satisfies the
Iterator<T>
interface is an
Iterator<T>
. So, an
array index is not a Java
Iterator<T>
. However, the index could be an instance vari-
able in an object of an
Iterator<T>
class.
An
Iterator<T>
object does not stand on its own. It must be associated with some
collection object. How is the association accomplished? In Java, any class that satisfies
the
Collection<T>
interface must have a method, named
iterator( )
, that returns an
Iterator<T>
. For example, let's say
c
is an instance of the
HashSet<T>
collection class with
some class plugged in for
T
. To make things concrete, let's plug in
String
for
T
; so
c
is an
instance of the
HashSet<String>
collection class. You can obtain an iterator for
c
as follows:
Iterator<T>
interface
Iterator<String> iteratorForC = c.iterator( );