Java Reference
In-Depth Information
fields for the methods
previous
and
add
, but the logic would be more involved than necessary.
Instead, let's define a boolean field to indicate whether a call to either
remove
or
set
is legal:
private boolean
isRemoveOrSetLegal;
If either
remove
or
set
finds this field to be false, it should throw an
IllegalStateException
. This
field should be initialized to false by the constructor. The methods
next
and
previous
should set it
to true, and the methods
add
and
remove
should set it to false.
Both
remove
and
set
must know which of
next
or
previous
was called so that they can access
the correct list entry. Thus, we define a data field to track the last call to these methods and an enu-
meration to provide values for the field. The following enumeration will suffice:
private enum
Move {NEXT, PREVIOUS}
Since an enumeration is really a class, we define it outside of the inner class
IteratorForArrayList
,
but within
ArrayListWithListIterator
. The data field then is simply
private
Move lastMove;
In addition to these two data fields, we need a field
nextIndex
to track the index of the next
entry in the iteration. This field is just like the one we described earlier in Segment 15.25. Thus, the
inner class begins as follows:
private class
IteratorForArrayList
implements
ListIterator
<
T>
{
private int
nextIndex;
private boolean
isRemoveOrSetLegal;
private
Move lastMove;
private
IteratorForArrayList()
{
nextIndex = 0;
isRemoveOrSetLegal =
false
;
lastMove =
null
;
}
// end default constructor
. . .
15.44
The method
hasNext
. The method
hasNext
has the same implementation that it had earlier in
Segment 15.26. Recall that it returns true if the iterator has not reached the end of the list.
public boolean
hasNext()
{
return
nextIndex < numberOfEntries;
}
// end hasNext
15.45
The method
next
. The implementation of
next
is similar to the one given in Segment 15.27. Here,
however, it has different fields to set. We set
lastMove
to
Move.NEXT
and
isRemoveOrSetLegal
to true.
public
T next()
{
if
(hasNext())
{
lastMove = Move.NEXT;
isRemoveOrSetLegal =
true
;
T nextEntry = list[nextIndex];
nextIndex++;
return
nextEntry;
}
else
throw new
NoSuchElementException("Illegal call to next(); " +
"iterator is after end of list.");
}
// end next