Java Reference
In-Depth Information
wasNextCalled = false ; // reset flag
}
else
throw new IllegalStateException("Illegal call to remove(); " +
"next() was not called.");
} // end remove
To call the list's method remove , which is defined in the outer class, from within the iterator's
remove , we must precede the name of the list's method with ArrayListWithIterator.this .
Question 10 Consider the list and the calls to next and remove in Figure 15-8.
a.
What would a call to next return if it occurred after the call to remove in Figure 15-8c?
b.
What would a call to next return if it occurred after the call to next in Figure 15-8b?
Question 11 What changes would be necessary to the methods in the inner class Iterator -
ForArrayList if its constructor set nextIndex to - 1 instead of 0?
Why Are Iterator Methods in Their Own Class?
15.29
Both separate class iterators and inner class iterators enable us to have several distinct iterations of
a data collection in progress at the same time. Because inner class iterators have direct access to the
structure containing the ADT's data, they can execute faster than separate class iterators, and so are
usually preferable.
Why didn't we simply consider the iterator operations as additional ADT operations? To answer
this question, let's modify the linked implementation of the list given in the previous chapter by includ-
ing the methods specified in Java's interface Iterator . To keep this implementation simple, we will not
provide the remove operation specified in Iterator . The resulting class, outlined in Listing 15-6, is
actually quite similar to the class LinkedListWithIterator , described in Segment 15.19, which imple-
ments an inner class iterator. The differences between these classes are highlighted.
The inner class IteratorForLinkedList shown in Segment 15.19 does not appear in our new
class, but its data field nextNode and its iterator methods hasNext , next , and remove do appear
unchanged. Instead of the inner class's constructor, we have the public method resetTraversal ,
which sets nextNode to firstNode . We'll call this method before we begin a traversal.
LISTING 15-6
An outline of the class ListWithTraversal
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ListWithTraversal<T> implements ListInterface<T>,
Iterator<T>
{
private Node firstNode;
private int numberOfEntries;
private Node nextNode; // node containing next entry in iteration
public ListWithTraversal()
{
clear();
} // end default constructor
 
 
Search WWH ::




Custom Search