Java Reference
In-Depth Information
iterators and nested classes
15.1
We begin by reviewing the simple iterator implementation first described in
Section 6.2. Recall that we defined a simple iterator interface, which mimics
the standard (nongeneric) Collections API Iterator , and this interface is
shown in Figure 15.1.
We then defined two classes: the container and its iterator. Each container
class is responsible for providing an implementation of the iterator inter-
face. In our case, the implementation of the iterator interface is provided by
the MyContainerIterator class, shown in Figure 15.2. The MyContainer class
shown in Figure 15.3 provides a factory method that creates an instance of
MyContainerIterator and returns this instance using the interface type Itera-
tor . Figure 15.4 provides a main that illustrates the use of the container/iterator
combination. Figures 15.1 to 15.4 simply replicate Figures 6.5 to 6.8 in the
original iterator discussion from Section 6.2.
1 package weiss.ds;
2
3 public interface Iterator
4 {
5 boolean hasNext( );
6 Object next( );
7 }
figure 15.1
The Iterator
interface from
Section 6.2
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 15.2
Implementation of the
MyContainerIterator
from Section 6.2
 
 
Search WWH ::




Custom Search