Java Reference
In-Depth Information
1
// An iterator class that steps through a MyContainer.
2
3
package weiss.ds;
4
5
public class MyContainerIterator
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.4
Implementation of the
MyContainerIterator
,
design 1
MyContainer
class implementation completely unchanged. On the other
hand, doing so illustrates no new principles.
Note that in the implementation of
MyContainer
, the data members
items
and
size
are package visible, rather than being private. This unfortunate relaxation
of the usual privacy of data members is necessary because these data members
need to be accessed by
MyContainerIterator
. Similarly, the
MyContainerIterator
constructor is package visible, so that it can be called by
MyContainer
.
6.2.2
inheritance-based iterators and factories
The iterator designed so far manages to abstract the concept of iteration into
an iterator class. This is good, because it means that if the collection changes
from an array-based collection to something else, the basic code such as lines
10 and 11 in Figure 6.2 does not need to change.
While this is a significant improvement, changes from an array-based col-
lection to something else require that we change all the declarations of the
iterator. For instance, in Figure 6.2, we would need to change line 9. We dis-
cuss an alternative in this section.
Our basic idea is to define an interface
Iterator
. Corresponding to each
different kind of container is an iterator that implements the
Iterator
proto-
col. In our example, this gives three classes:
MyContainer
,
Iterator
, and
MyContainerIterator
. The relationship that holds is
MyContainerIterator
IS-A
Iterator
. The reason we do this is that each container can now create an
appropriate iterator, but pass it back as an abstract
Iterator
.
An inheritance-
based iteration
scheme defines an
iterator interface.
Clients program to
this interface.
Search WWH ::
Custom Search