Java Reference
In-Depth Information
FIGURE 15-9
The effect of a call to
previous
on a list
(a) Before
previous()
(b) After
previous()
returns
Joey
Jamie
Joey
Rachel
Monica
Ross
Jamie
Joey
Rachel
Monica
Ross
Iterator cursor
Iterator cursor
15.36
The indices of the current and previous entries.
As Figure 15-10 shows, the methods
nextIndex
and
previousIndex
each return the index of the entry that a subsequent call to
next
or
previous
,
respectively, would return. Note that the iterator numbers the list's entries beginning with 0, instead
of 1 as the ADT list operations do. If a call to
next
would throw an exception because the iterator is
at the end of the list,
nextIndex
returns the size of the list. Similarly, if a call to
previous
would
throw an exception because the iterator is at the beginning of the list,
previousIndex
returns
-
1.
FIGURE 15-10
The indices returned by the methods
nextIndex
and
previousIndex
Jamie
Joey
Rachel
Monica
Ross
previousIndex()
returns the index of
Joey
nextIndex()
returns the index of
Rachel
Iterator cursor
Note:
The interface
ListIterator
specifies nine methods, including the three methods
that
Iterator
specifies. They are
hasNext
,
hasPrevious
,
next
,
previous
,
nextIndex
,
previousIndex
,
add
,
remove
, and
set
.
15.37
Example: Traversals.
Let's look at an example of the methods that work with the current and
previous entries and then use it to describe the remaining methods in the interface. We make the
following assumptions:
The interface
ListIterator
is implemented as an inner class of the class that implements
the ADT list.
●
The iterator includes the operations
add
,
remove
, and
set
.
●
The method
getIterator
is added to the ADT list.
●
The list
nameList
contains the following names:
Jess
Jim
Josh
●
The iterator
traverse
is defined as follows:
●
ListIterator<String> traverse = nameList.getIterator();