Java Reference
In-Depth Information
Display 16.14
For-Each Loops as Iterators
(part 2 of 2)
18
s.remove(last);
19
System.out.println( );
20
System.out.println("The set now contains:");
21
for
(String e : s)
22
System.out.println(e);
23
System.out.println("End of program.");
24
}
25
}
The output is the same as in Display 16.13.
List Iterators
The collection framework has two iterator interfaces: the
Iterator<T>
interface, which
you have already seen and that works with any collection class that implements the
Collection<T>
interface, and the
ListIterator<T>
interface, which is designed to work
with collections that implement the
List<T>
interface. The
ListIterator<T>
inter-
face extends the
Iterator<T>
interface. A
ListIterator<T>
has all the methods
that an
Iterator<T>
has, plus more methods that provide two new abilities: a
ListIterator<T>
can move in either direction along the list of elements in the collec-
tion, and a
ListIterator<T>
has methods, such as set and add, that can be used to change
the elements in the collection. The methods for the
ListIterator<T>
interface are
given in Display 16.15. See Appendix 5 for a more detailed description that includes
all exceptions thrown.
The map framework does not directly support the iterable interface, but you can
use the map's
keySet( )
,
values( )
, or
entrySet( )
methods, which return iterable
sets containing the keys, values, or (key, value) mappings of the map.
ListIterator
<T>
Display 16.15
Methods in the
ListIterator<T>
Interface
(part 1 of 2)
The
ListIterator <T>
interface is in the
java.util
package.
The
cursor position
is explained in the text and in Display 16.16.
All the exception classes mentioned are the kind that are not required to be caught in a
catch
block or declared in a
throws
clause.
NoSuchElementException
is in the
java.util
package, which requires an import statement if
your code mentions the
NoSuchElementException
class. All the other exception classes men-
tioned are in the package
java.lang
and so do not require any import statement.
public
T next( )
Returns the next element of the list that produced the iterator. More specifically, returns the ele-
ment immediately after the cursor position.
Throws a
NoSuchElementException
if there is no next element.
(continued)