Java Reference
In-Depth Information
index of the element that a subsequent invocation of
next
or
previous
will return. The next index when the iterator is at the end of the list is
returned as
list.size()
. The previous index when the iterator is at the
first element in the list (index
0
) is returned as 1.
The
remove
method on a
ListIterator
removes the last value returned by
either
next
or
previous
. In addition to
remove
, you can use two additional
methods to modify the list's contents:
public void
set(E elem)
Replaces the last element returned by
next
or
previous
with
elem
. If you have called
remove
or
add
on the iterator since the
last call to
next
or
previous
, calling
set
throws
IllegalStateEx-
ception
. (Optional)
public void
add(E elem)
Inserts
elem
into the list in front of the next element that
would be returned, or at the end if
hasNext
returns
false
. The
iterator is moved forward; if you invoke
previous
after an
add
you will get the added element. (Optional)
The contract of
remove
is extended such that an
IllegalStateException
is
thrown if
remove
is invoked and either
set
or
add
has been invoked since
the last call to
next
or
previous
.
The contracts for
Iterator
and
ListIterator
do not include a
snapshot
guarantee. In other words, changing the contents of the collection while
the iterator is in use can affect the values returned by the methods. For
example, if the implementation of
next
uses the contents of the original
collection for its list, it is dangerous to remove elements from the list
as you step through it except through the iterator's own methods. A
snapshot would return the elements as they were when the
Iterator
or
ListIterator
object was created, immune from future changes. You can
rely on having a snapshot of the contents only if the method that returns
an iterator object explicitly makes a snapshot guarantee. If you need a