through a different iterator on the same collection) is unsafe.
The ListIterator
ordered List object during iteration. You can iterate forward using hasNext and next, backward using
hasPrevious and previous, or back and forth by intermixing the calls as you please. The following
code loops backward through a list of strings:
ListIterator
while (it.hasPrevious()) {
String obj = it.previous();
System.out.println(obj);
// ... use obj ...
}
This gets a ListIterator positioned one beyond the end of the list, and then backs up through the list one
element at a time, printing each element. List elements are indexed by position, just like array elements, from
0 to list.size()-1. The methods nextIndex or previousIndex get the 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 voidset(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 IllegalStateException. (Optional)
public voidadd(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 snapshot but
don't have such a guarantee, you can create a snapshot by making a simple copy of the collection, such as with
an ArrayList:
public
snapshotIterator(Collection<? extends T> coll) {
return new ArrayList
}