Java Reference
In-Depth Information
for( int i = 0; i < v.length; i++ )
System.out.println( v[ i ] );
In this loop, i is an iterator object, because it is the object that is used to con-
trol the iteration. However, using the integer i as an iterator constrains the
design: We can only store the collection in an array-like structure. A more
flexible alternative is to design an iterator class that encapsulates a position
inside of a collection. The iterator class provides methods to step through the
collection.
The key is the concept of programming to an interface: We want the code
that performs access of the container to be as independent of the type of the
container as possible. This is done by using only methods that are common to
all containers and their iterators.
There are many different possible iterator designs. If we replace int i
with IteratorType itr , then the loop above expresses
When we program
to an interface, we
write code that
uses the most
abstract methods.
These methods
will be applied to
the actual con-
crete types.
for( itr = v.first( ); itr.isValid( ); itr.advance( ) )
System.out.println( itr.getData( ) );
This suggests an iterator class that contains methods such as isValid , advance ,
getData , and so on.
We describe two designs, outside the Collections API context, that lead to
the Collections API iterator design. We discuss the specifics of the Collections
iterators in Section 6.3.2, deferring implementations to Part IV.
6.2.1 basic iterator design
The first iterator design uses only three methods. The container class is
required to provide an iterator method. iterator returns an appropriate itera-
tor for the collection. The iterator class has only two methods, hasNext and
next . hasNext returns true if the iteration has not yet been exhausted. next
returns the next item in the collection (and in the process, advances the cur-
rent position). This iterator interface is similar to the interface provided in the
Collections API.
To illustrate the implementation of this design, we outline the collection
class and provide an iterator class, MyContainer and MyContainerIterator ,
respectively. Their use is shown in Figure 6.2. The data members and iterator
method for MyContainer are written in Figure 6.3. To simplify matters, we omit
the constructors, and methods such as add , size , etc. The ArrayList class from
earlier chapters can be reused to provide an implementation of these methods.
We also avoid use of generics for now.
iterator returns
an appropriate
iterator for the col-
lection.
 
Search WWH ::




Custom Search