Java Reference
In-Depth Information
1 public static void main( String [] args )
2 {
3 MyContainer v = new MyContainer( );
4
5 v.add( "3" );
6 v.add( "2" );
7
8 System.out.println( "Container contents: " );
9 MyContainerIterator itr = v.iterator( );
10 while( itr.hasNext( ) )
11 System.out.println( itr.next( ) );
12 }
figure 6.2
A main method, to
illustrate iterator
design 1
1 package weiss.ds;
2
3 public class MyContainer
4 {
5 Object [ ] items;
6 int size;
7
8 public MyContainerIterator iterator( )
9 { return new MyContainerIterator( this ); }
10
11 // Other methods
12 }
figure 6.3
The MyContainer class,
design 1
The iterator method in class MyContainer simply returns a new iterator;
notice that the iterator must have information about the container that it is iter-
ating over. Thus the iterator is constructed with a reference to the MyContainer .
Figure 6.4 shows the MyContainerIterator . The iterator keeps a variable
( current ) that represents the current position in the container, and a reference
to the container. The implementation of the constructor and two methods is
straightforward. The constructor initializes the container reference, hasNext
simply compares the current position with the container size, and next uses the
current position to index the array (and then advances the current position).
The iterator is con-
structed with a
reference to the
container that it
iterates over.
A limitation of this iterator design is the relatively limited interface.
Observe that it is impossible to reset the iterator back to the beginning, and
that the next method couples access of an item with advancing. The next ,
hasNext design is what is used in the Java Collections API; many people
feel that the API should have provided a more flexible iterator. It is cer-
tainly possible to put more functionality in the iterator, while leaving the
The better design
would put more
functionality in the
iterator.
Search WWH ::




Custom Search