Java Reference
In-Depth Information
Remember, remove must throw an exception if the field isRemoveOrSetLegal is false. If the
field is true, the method must set it to false. An implementation of remove follows:
public void remove()
{
if (isRemoveOrSetLegal)
{
isRemoveOrSetLegal = false ;
if (lastMove.equals(Move.NEXT))
{
// next() called, but neither add() nor remove() has been
// called since
// nextIndex is 1 more than the index of the entry returned
// by next(), so it is the position number of the entry
// to be removed
ArrayListWithListIterator. this .remove(nextIndex);
nextIndex--;
}
else
{
// previous() called, but neither add() nor remove() has been
// called since
assert lastMove.equals(Move.PREVIOUS);
// nextIndex is the index of the entry returned by previous(),
// so it is 1 less than the position number of the entry
// to be removed
ArrayListWithListIterator. this .remove(nextIndex + 1);
} // end if
}
else
throw new IllegalStateException("Illegal call to remove(); " +
"next() or previous() was not called, OR "
"add() or remove() called since then.");
} // end remove
15.50
The method set . The method set replaces the last entry in the list that either next or previous has
returned. It uses nextIndex , as updated by either of the methods next or previous . Since the method
next returns list[nextIndex] and then increments nextIndex , the method set would replace the
object in list[nextIndex - 1] after a call to next . Likewise, since previous decrements nextIndex
and then returns list[nextIndex] , the method set would replace list[nextIndex] after a call to
previous .
The following implementation of set reflects these observations and uses the same logic that
we used in remove to see whether to throw IllegalStateException :
public void set(T newEntry)
{
if (isRemoveOrSetLegal)
{
if (lastMove.equals(Move.NEXT))
list[nextIndex - 1] = newEntry;
else
{
assert lastMove.equals(Move.PREVIOUS);
list[nextIndex] = newEntry;
} // end if
}
else
Search WWH ::




Custom Search