Java Reference
In-Depth Information
private Node position;
private Node previous;
}
. . .
}
Each iterator object has a reference
position
to the last visited node. We also store
a reference to the last node before that. We will need that reference to adjust the links
properly in the
remove
method.
The
next
method is simple. The
position
reference is advanced to
position.next
, and the old position is remembered in
previous
. There is a
special case, howeverȌif the iterator points before the first element of the list, then
the old
position
is
null
, and
position
must be set to
first
.
private class LinkedListIterator
implements ListIterator
{
. . .
public Object next()
{
if (!hasNext())
throw new NoSuchElementException();
previous = position;
// Remember for remove
if (position == null)
position = first;
else
position = position.next;
return position.data;
}
. . .
}
674
675
The
next
method is supposed to be called only when the iterator is not yet at the end
of the list. The iterator is at the end if the list is empty (that is,
first == null
) or
if there is no element after the current position (
position.next == null
).
private class LinkedListIterator
implements ListIterator
{
. . .
public boolean hasNext()
{