Java Reference
In-Depth Information
21.2. Iteration
You've encountered iteration several times already during the course of
10
. This section reviews the basic operation of an iterator and covers its
additional capabilities and the additional iterator types.
Collection<E>
extends
Iterable<E>
, which defines an
iterator
method that
returns an object that implements the
Iterator<E>
interface:
public boolean
hasNext()
Returns
true
if the iteration has more elements.
public E
next()
Returns the next element in the iteration. If there is no next
element a
NoSuchElementException
is thrown.
public void
remove()
Removes the element returned most recently by the iteration
from the underlying collection.
remove
can be called only once
per call of
next
. If
next
has not yet been called, or if
remove
has already been called since the last call to
next
, an
Illeg-
alStateException
is thrown. (Optional)
The following code uses all three methods of
Iterator
to remove all long
strings from a collection:
public void removeLongStrings
(Collection<? extends String> coll, int maxLen) {
Iterator<? extends String> it = coll.iterator();
while (it.hasNext()) {
String str = it.next();
if (str.length() > maxLen)