Java Reference
In-Depth Information
1 // An iterator class that steps through a MyContainer.
2
3 package weiss.ds;
4
5 class MyContainerIterator implements Iterator
6 {
7 private int current = 0;
8 private MyContainer container;
9
10 MyContainerIterator( MyContainer c )
11 { container = c; }
12
13 public boolean hasNext( )
14 { return current < container.size; }
15
16 public Object next( )
17 { return container.items[ current++ ]; }
18 }
figure 6.7
Implementation of the
MyContainerIterator ,
design 2
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 Iterator itr = v.iterator( );
10 while( itr.hasNext( ) )
11 System.out.println( itr.next( ) );
12 }
figure 6.8
A main method, to
illustrate iterator
design 2
collections api:
containers and iterators
6.3
This section describes the basics of the Collections API iterators and how they
interact with containers. We know that an iterator is an object that is used to
traverse a collection of objects. In the Collections API such a collection is
abstracted by the Collection interface, and the iterator is abstracted by the
Iterator interface.
The Collections API iterators are somewhat inflexible, in that they pro-
vide few operations. These iterators use an inheritance model described in
Section 6.2.2.
 
 
Search WWH ::




Custom Search