Java Reference
In-Depth Information
15.3
The package
java.util
in the Java Class Library contains two interfaces—
Iterator
and
ListIterator
—that specify methods appropriate for an iterator. Let's begin by examining
the interface
Iterator
, given in Listing 15-1. Like many of the interfaces we have consid-
ered,
Iterator
specifies a generic type to represent the data type of the entries involved in
the iteration. It specifies only three methods—
hasNext
,
next
, and
remove
—that an iterator
can have. These methods enable you to traverse a collection of data from its beginning.
LISTING 15-1
Java's interface
java.util.Iterator
package
java.util;
public
interface
Iterator<T>
{
/** Detects whether this iterator has completed its traversal
and gone beyond the last entry in the collection of data.
@return true if the iterator has another entry to return */
public
boolean
hasNext();
/** Retrieves the next entry in the collection and
advances this iterator by one position.
@return a reference to the next entry in the iteration,
if one exists
@throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false */
public
T next();
/** Removes from the collection of data the last entry that
next() returned. A subsequent call to next() will behave
as it would have before the removal.
Precondition: next() has been called, and remove() has not been
called since then. The collection has not been altered
during the iteration except by calls to this method.
@throws IllegalStateException if next() has not been called, or
if remove() was called already after the last call to
next().
@throws UnsupportedOperationException if the iterator does
not permit a remove operation. */
public
void
remove();
// Optional method
}
// end Iterator
15.4
An iterator marks its current position within a collection much as your finger can point to an entry in a
list or to a line on this page. However, in Java, the position of an iterator is not
at
an entry. Instead, it
is positioned either before the first entry in the collection, between two entries, or after the last entry.
The
next entry
in an iteration is the one right after the position of the iterator's
cursor
.
The method
hasNext
sees whether a next entry exists and returns true or false accordingly.
As long as
hasNext
returns true, the method
next
moves the iterator's cursor over the next
entry and returns a reference to it, as Figure 15-1 illustrates. Repeated calls to
next
traverse through