Java Reference
In-Depth Information
15.46
The methods hasPrevious and previous . The methods hasPrevious and previous have imple-
mentations that are analogous to those of hasNext and next , respectively.
public boolean hasPrevious()
{
return (nextIndex > 0) && (nextIndex <= numberOfEntries);
} // end hasPrevious
public T previous()
{
if (hasPrevious())
{
lastMove = Move.PREVIOUS;
isRemoveOrSetLegal = true ;
nextIndex--;
return list[nextIndex];
}
else
throw new NoSuchElementException("Illegal call to previous(); " +
"iterator is before beginning of list.");
} // end previous
15.47
The methods nextIndex and previousIndex . The method nextIndex returns either the index of
the entry that the method next would return if called or the size of the list if the iterator is after the
end of the list.
public int nextIndex()
{
int result;
if (hasNext())
result = nextIndex;
else
result = numberOfEntries;
return result;
} // end nextIndex
The method previousIndex returns either the index of the entry that the method previous would
return if called or - 1 if the iterator is before the beginning of the list.
public int previousIndex()
{
int result;
if (hasPrevious())
result = nextIndex - 1;
else
result = -1;
return result;
} // end previousIndex
15.48
The method add . The method add inserts an entry into the list just before the iterator's current
position, that is, immediately before the entry in list[nextIndex] , as Figure 15-12 illustrates. To
avoid duplicate code and effort, we call the list's add method to add an entry at position nextIndex
+ 1 within the list. Recall that entries after the new entry will be shifted and renumbered. Therefore,
we need to increment nextIndex so that it will continue to mark the entry that a subsequent call to
next would return. If we increment nextIndex before calling add , we can pass nextIndex to add as
the position of the insertion. Thus, add has the following implementation:
public void add(T newEntry)
{
Search WWH ::




Custom Search