Java Reference
In-Depth Information
private IteratorForLinkedList()
{
nextNode = firstNode;
} // end default constructor
< Implementations of the methods in the interface Iterator go here;
you can see them in Segments 15.21 through 15.23.>
. . .
} // end IteratorForLinkedList
< Implementation of the private class Node (Listing 3-4 of Chapter 3) goes here. >
. . .
} // end LinkedListWithIterator
15.20
The inner class IteratorForLinkedList . As you can see in Listing 15-4, the private inner class
IteratorForLinkedList has a data field nextNode to track an iteration. The constructor initializes
this field to firstNode , which is a data field of the outer class and references the first node in the
chain that contains the list's entries. We cannot position the iterator between nodes, even though we
imagine its position to be between entries. Nor can nextNode reference the node before the one that
next will access, because the first node has no node before it. Thus, nextNode references the next
node in the iteration, that is, the node that the method next must access to get the next entry.
Note: An inner class can refer to its outer class's data fields by name alone, if it does not also use
the same names for its own definitions. For example, the constructor of the inner class Iterator -
ForLinkedList references the field firstNode directly by name since no other firstNode exists.
But we could have written LinkedListWithIterator.this.firstNode instead.
Figure 15-7 illustrates an inner class iterator. The iterator has direct access to the ADT's under-
lying data structure—a linked chain, in this example. Since the data field nextNode maintains the
current position of the iteration, the iterator can quickly retrieve the next entry in the iteration with-
out first returning to the beginning of the chain.
We now implement the methods of the interface Iterator within the inner class. These
methods will be public, even though they appear within a private class, because they are public
in Iterator and will be used by clients of LinkedListWithIterator .
FIGURE 15-7
An inner class iterator with direct access to the linked chain that
implements the ADT
An inner class
iterator
nextNode
Ken
An ADT list
Sue
To m
Jen
Bob
Iterator cursor
 
 
Search WWH ::




Custom Search