Java Reference
In-Depth Information
You have added a nested class to define an iterator object for a linked list. The
ListIterator
class
defines the methods declared in the
Iterator<T>
interface plus a constructor. Note that you do not need
to specify a type parameter for the
ListIterator
class. Only the interface that is implemented by the
ListIterator
class is parameterized, and that uses the type variable name for the outer class. The type ar-
gument you supply for the container type also applies to the methods declared by the
Iterator<T>
interface
that are implemented by
ListIterator
.
A
ListIterator
object is able to access the members of its parent
LinkedList<T>
object directly, but
because it must provide a one-pass iteration through the elements in the linked list, it needs to track what is
happening during successive calls of the
next()
method. You can provide this by adding a field of type
T
to
the
ListIterator
class to record the element from the linked list that is available when the
next()
method
is called. You can easily initialize such a field in the constructor and then implement the other methods to
make use of it. The inner class definition would then look like this:
private class ListIterator implements Iterator<T> {
// Constructor
public ListIterator() {
nextElement = getFirst();
}
// Method to test whether more elements are available
public boolean hasNext() {
return nextElement != null;
}
// Method to return the next available object from the linked list
public T next() {
T element = nextElement;
if(element == null) {
throw new java.util.NoSuchElementException();
}
nextElement = getNext();
return element;
}
// Method to remove the last element retrieved from the linked list
// You don't want to support this operation so just throw the exception
// If you did support this operation, you would need to include a check
// that next() has been called, and if not,
// throw IllegalStateException
public void remove() {
throw new UnsupportedOperationException(
"Remove not supported for LinkedList<>");
}
private T nextElement;
}
If you add this inner class to the definition of
LinkedList<>
, you can use a new version of the
TryAuto-
boxing
example to try it out.