Java Reference
In-Depth Information
Internally, the local variable
position
references the current node in the linked list,
whereas the local variable
previous
references the node linking to the current node.
The purpose of the
previous
variable will be seen when adding and deleting nodes. In
the constructor and the
restart( )
method,
position
is set to
head
and
previous
is set to
null
.
To determine if the end of the list has been reached,
hasNext( )
returns whether
or not
position
is
null
:
return
(position !=
null
);
To step through the list, the
next( )
method first throws an exception if we have
reached the end of the list:
if
(!hasNext( ))
throw new
NoSuchElementException( );
Otherwise, the method retrieves the string value of the iterator referenced by
position
in the variable
toReturn
, advances
previous
to reference the current position,
advances
position
to the next node in the list, and returns the string:
String toReturn = position.item;
previous = position;
position = position.link;
return
toReturn;
The definition of the method
changeHere
is left to Self-Test Exercise 13. (If
necessary, you can look up the definition in the answer to Self-Test Exercise 13.) The
techniques for adding and deleting nodes are discussed in the next subsection.
The Java
Iterator
Interface
Java has an interface named
Iterator
that specifies how Java would like an iterator to
behave. It is in the package
java.util
(and so requires that you import this package). Our
iterators do not quite satisfy this interface, but they are in the same general spirit as that
interface and could be easily redefined to satisfy the
Iterator
interface.
The
Iterator
interface is discussed in Chapter 16.
Adding and Deleting Nodes
To add or delete a node in a linked list, you normally use an iterator and add or delete
a node at the (approximate) location of the iterator. Because deleting is a little easier
than adding a node, we will discuss deleting first.