THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
NoSuchElementException if the collection is empty.
Methods or constructors that take parameters of reference type usually throw
NullPointerException if passed a null reference. The exceptions to this are collections that
accept null elements, with which null can be used when adding, removing, or searching.


Any variations to the above, or other exceptions generated, are documented on a case-by-case basis.


21.2. Iteration


You've encountered iteration several times already during the course of this bookparticularly in the discussion
of the enhanced for loop in Chapter 10. This section reviews the basic operation of an iterator and covers its
additional capabilities and the additional iterator types.


Collection extends Iterable, which defines an iterator method that returns an object that
implements the Iterator interface:


public booleanhasNext()

Returns true if the iteration has more elements.

public Enext()

Returns the next element in the iteration. If there is no next element a
NoSuchElementException is thrown.

public voidremove()

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 IllegalStateException 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)
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 enhanced 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 iterator'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

Free download pdf