Java Reference
In-Depth Information
15.16
By using separate class iterators, you can have multiple and distinct iterations of a list exist simulta-
neously. However, separate class iterators belong to a public class, so they can access the list's data
fields only indirectly via ADT operations. As a result, the iterations take more time than those per-
formed by other kinds of iterators. For ADTs other than a list, a separate class iterator might have
insufficient access to the data fields to perform an iteration.
A desirable alternative is to define the iterator class as an inner class of the ADT. Because the
resulting iterator objects are distinct from the ADT, you can have multiple iterations in progress at
the same time. Moreover, since the iterator belongs to an inner class, it has direct access to the
ADT's data fields. For these reasons, an inner class iterator is usually preferable to a separate class
iterator.
In this section, we will implement the interface
Iterator
by adding an inner class to each of
two implementations of the ADT list. First, we will use a linked implementation of the list but will
provide only the iterator operations
hasNext
and
next
. Then we will use an array-based list and
support all three operations of
Iterator
.
VideoNote
Alternative iterator
implementations
15.17
To achieve our goal, we must define the methods specified in
Iterator
within a new inner class of
the class that implements the ADT list. We'll name this inner class
IteratorForLinkedList
and
name the outer class
LinkedListWithIterator
. The outer class will be much like the class
LList
of Chapter 14. However, it needs another method that the client can use to create an iterator. This
method,
getIterator
, has the following simple implementation:
public
Iterator<T> getIterator()
{
return new
IteratorForLinkedList();
}
// end getIterator
We will show you how to use this method shortly.
To accommodate this new method, we create a new interface—shown in Listing 15-3—that extends
ListInterface
instead of changing it. This interface has all the list methods of
ListInterface
and the
new method
getIterator
.
LISTING 15-3
The interface
ListWithIteratorInterface
import
java.util.Iterator;
public
interface
ListWithIteratorInterface<T>
extends
ListInterface<T>
{
public
Iterator<T> getIterator();
}
// end ListWithIteratorInterface
Because a class can implement more than one interface, we could define the class
LinkedListWithIterator
without using our new interface. But having this interface enables us to
declare an object of type
ListWithIteratorInterface
and know that the object will have the list
methods as well as the method
getIterator
.