Java Reference
In-Depth Information
< Segment 15.25 begins a description of the following inner class. >
private
class
IteratorForArrayList
implements
Iterator<T>
{
private
int
nextIndex;
private
boolean
wasNextCalled;
// needed by remove
private
IteratorForArrayList()
{
nextIndex = 0;
wasNextCalled =
false
;
}
// end default constructor
< Implementations of the methods in the interface
Iterator
go here;
you can see them in Segments 15.26 through 15.28. >
. . .
}
// end IteratorForArrayList
}
// end ArrayListWithIterator
15.25
The inner class
IteratorForArrayList
.
Just as you can use your finger to keep track of your
place on this page, our iterator implementation uses an index to keep track of the iterator's position
within the array of list entries. This index, which we call
nextIndex
, is a data field of the private
inner class
IteratorForArrayList
. It will be the index of the next entry in the iteration. The con-
structor initializes
nextIndex
to zero, as Listing 15.5 shows.
Just as you saw earlier in Segments 15.12 and 15.15, providing an iterator with a remove oper-
ation requires an additional data field that the
remove
method can use to see whether
next
was
called. Again, we name this data field
wasNextCalled
, but here it is defined within the inner class.
The constructor initializes this field to false.
15.26
The method
hasNext
.
The iterator has a next entry to retrieve if
nextIndex
is less than the length
of the list. Thus,
hasNext
has the following straightforward implementation:
public boolean
hasNext()
{
return
nextIndex < numberOfEntries;
}
// end hasNext
Notice that
hasNext
returns false when the list is empty, that is, when
numberOfEntries
is zero.
15.27
The method
next
.
The implementation of the method
next
has the same general form as the ver-
sion given in Segment 15.14 for the separate class iterator. If
hasNext
returns true,
next
returns the
next entry in the iteration. Here, the next entry is
list[nextIndex]
. The method also advances the
iteration by incrementing
nextIndex
and sets the flag
wasNextCalled
to true. On the other hand, if
hasNext
returns false,
next
throws an exception.
public
T next()
{
if
(hasNext())
{
wasNextCalled =
true
;
T nextEntry = list[nextIndex];