Java Reference
In-Depth Information
15.21
The method
next
.
If the iteration has not ended,
nextNode
references the node containing the next
entry in the iteration. Thus,
next
can easily get a reference to this entry. The method then must
advance
nextNode
to the next node and return the retrieved list entry. However,
next
must throw an
exception if the iteration has already ended.
public
T next()
{
if
(hasNext())
{
Node returnNode = nextNode;
// get next node
nextNode = nextNode.getNextNode();
// advance iterator
return
returnNode.getData();
// return next entry in iteration
}
else
throw new
NoSuchElementException("Illegal call to next(); " +
"iterator is after end of list.");
}
// end next
15.22
The method
hasNext
.
After the method
next
returns the last entry in the iteration,
nextNode
will
be
null
, since
null
is in the link portion of the last node in the chain. The method
hasNext
can sim-
ply compare
nextNode
with
null
to see whether the iteration has ended:
public boolean
hasNext()
{
return
nextNode !=
null
;
}
// end hasNext
Question 7
What does the method
hasNext
return when the list is empty? Why?
15.23
The method
remove
.
Even though we decided not to support a
remove
operation for this iterator, we
must implement the method because it is declared in the interface
Iterator
. If the client invokes
remove
, the method simply throws the run-time exception
UnsupportedOperationException
. Here
is an example of how you can define
remove
:
public void
remove()
{
throw new
UnsupportedOperationException("remove() is not " +
"supported by this iterator");
}
// end remove
This exception is in the package
java.lang
and so is included automatically in every Java program.
Thus, an
import
statement is unnecessary.
Note:
The
remove
method
An iterator that does not allow the removal of items during a traversal is not unusual. In such
cases, the
remove
method is defined, but it throws an exception if invoked.
Note:
Inner class iterators
An inner class iterator has direct access to an ADT's data, so it typically can execute faster
than a separate class iterator. Its implementation is usually more involved, however. Both of
these iterators have another advantage: Several iterator objects can be in existence at the
same time and traverse a list independently of one another.