Java Reference
In-Depth Information
it.remove();
}
}
First we use
iterator
to get an
Iterator
object that steps through the
contents of the collection one element at a time (recall that the en-
hanced
for
loop can't be used when you want to remove elements using
the iterator). Then we loop as long as
hasNext
returns
true
to indicate
that there is at least one more element left in the iteration. Each time
through the loop we get the next element of the list using
next
. If any
string is longer than the maximum allowed length, we use the iterat-
or's
remove
method to remove the most recent element returned by
next
.
When you use an iterator's
remove
method you modify the underlying
collection safely for that iteratorthe iterator will properly move through
the subsequent elements of the collection. Removing elements from the
collection any other way (using operations on the collection or through
a different iterator on the same collection) is unsafe.
The
ListIterator<E>
interface extends
Iterator<E>
, adding methods you
can use to manipulate an 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<String> it = list.listIterator(list.size());
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 ele-
ment. List elements are indexed by position, just like array elements,
from
0
to
list.size()-1
. The methods
nextIndex
or
previousIndex
get the