Java Reference
In-Depth Information
specific meaning of keys in a hash table depends on how the table is used and the data it
contains.
The next section looks at these data structures in more detail to show how they work.
Iterator
The
Iterator
interface provides a standard means of iterating through a list of elements
in a defined sequence, which is a common task for many data structures.
Even though you can't use the interface outside a particular data structure, understanding
how the
Iterator
interface works helps you understand other Java data structures.
With that in mind, take a look at the methods defined by the
Iterator
interface:
public boolean hasNext() {
// body of method
}
public Object next() {
// body of method
}
public void remove() {
// body of method
}
The
hasNext()
method determines whether the structure contains any more elements.
You can call this method to see whether you can continue iterating through a structure.
The
next()
method retrieves the next element in a structure. If there are no more ele-
ments,
next()
throws a
NoSuchElementException
exception. To avoid this, you can use
hasNext()
in conjunction with
next()
to make sure that there is another element to
retrieve.
The following
while
loop uses these two methods to iterate through a data structure
called
users
that implements the
Iterator
interface:
while (users.hasNext()) {
Object ob = users.next();
System.out.println(ob);
}
This sample code displays the contents of each list item by using the
hasNext()
and
next()
methods.