Java Reference
In-Depth Information
The general idea of
next
and
previous
is clear, but we need to make it precise if you
are to understand the
next()
and
previous()
methods of the
ListIterator<T>
interface. Every
ListIterator<T>
has a position marker in the list known as the
cursor
. If the list has
n
elements, they are numbered by indices 0 through
n
-1,
but there are
n
+
1 cursor positions, as indicated in Display 16.16. When
next()
is
invoked, the element immediately following the cursor position is returned and the
cursor is moved to the next cursor position. When
previous()
is invoked, the element
immediately before the cursor position is returned, and the cursor is moved back to the
preceding cursor position.
cursor
The
ListIterator<T>
Interface
The
ListIterator<T>
interface extends the
Iterator<T>
interface. The
ListIterator<T>
interface differs from the
Iterator<T>
interface by adding the following abilities: A
ListIterator<T>
can move in either direction along the list of elements in the collection,
and a
ListIterator<T>
has methods, such as
set
and
add
, that can be used to change the
elements in the collection.
Display 16.16
ListIterator<T>
Cursor Positions
List
element 0 element 1 element 2 ... element
n
-1
Cursor positions
The default initial cursor position is the leftmost one.
PITFALL:
next
Can Return a Reference
If
i
is an iterator, then
i.next()
returns an element of the collection that created
i
,
but there are two meanings of “return an element.”
1. The invocation
i.next()
could return a copy of the element in the collection
(for example, using a copy constructor or a
clone
method).
2. Alternatively,
i.next()
could return a reference to the element in the collection.
In case (1), modifying
i.next()
will not
change the element in the collection (pro-
vided the copy was a deep copy). In case (2), modifying
i.next()
will
change the
element in the collection. The APIs for both the
Iterator<T>
and
ListIterator<T>
interfaces are vague on whether you should follow policy (1) or (2), but the iterators