Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 17: java.util Part 1: The Collections Framework 459


bidirectional traversal of a list, and the modification of elements.IteratorandListIterator
are generic interfaces which are declared as shown here:


interface Iterator<E>
interface ListIterator<E>

Here,Especifies the type of objects being iterated. TheIteratorinterface declares the methods
shown in Table 17-8. The methods declared byListIteratorare shown in Table 17-9. In both
cases, operations that modify the underlying collection are optional. For example,remove( )
will throwUnsupportedOperationExceptionwhen used with a read-only collection. Various
other exceptions are possible.


Using an Iterator


Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides aniterator( )method that returns an iterator to the start of
the collection. By using this iterator object, you can access each element in the collection, one


Method Description
boolean hasNext( ) Returnstrueif there are more elements. Other wise, returnsfalse.
E next( ) Returns the next element. ThrowsNoSuchElementExceptionif there is not
a next element.
void remove( ) Removes the current element. ThrowsIllegalStateExceptionif an attempt
is made to callremove( )that is not preceded by a call tonext( ).

TABLE 17-8 The Methods Defined byIterator


Method Description
void add(Eobj) Insertsobjinto the list in front of the element that will be returned
by the next call tonext( ).
boolean hasNext( ) Returnstrueif there is a next element. Other wise, returnsfalse.
boolean hasPrevious( ) Returnstrueif there is a previous element. Other wise, returnsfalse.
E next( ) Returns the next element. ANoSuchElementExceptionis thrown
if there is not a next element.
int nextIndex( ) Returns the index of the next element. If there is not a next element,
returns the size of the list.
E previous( ) Returns the previous element. ANoSuchElementExceptionis thrown
if there is not a previous element.
int previousIndex( ) Returns the index of the previous element. If there is not a previous
element, returns−1.
void remove( ) Removes the current element from the list. AnIllegalStateException
is thrown ifremove( )is called beforenext( )orprevious( )is invoked.
void set(Eobj) Assignsobjto the current element. This is the element last returned
by a call to eithernext( )orprevious( ).

TABLE 17-9 The Methods Defined byListIterator

Free download pdf