Java Reference
In-Depth Information
Method
Description
remove()
Removes the last object returned by
next()
from the collection that
supplied the
Iterator
object. If
next()
has not been called or if you call
remove()
twice after calling
next()
, an
IllegalStateException
will
be thrown. Not all iterators support this method, in which case an
UnsupportedOperationException
exception will be thrown if you call
it.
Since calling the
next()
method for an object that implements
Iterator
returns successive objects
from the collection, starting with the first, you can progress through all the objects in a collection very
easily with a loop such as:
MyClass item; // Store an object from the collection
while(iter.hasNext()) { // Check that there's another
item = (MyClass)iter.next(); // Retrieve next object
// Do something with item...
}
This assumes
iter
is of type
Iterator
and stores a reference to an object obtained from whatever
collection class we were using. As we shall see shortly, objects that are collections have a method,
iterator()
, that returns an iterator for the current contents of the collection. The loop continues as
long as the
hasNext()
method returns
true
. Since the
next()
method returns the object as type
Object
, we will usually need to cast it to its actual type. Each time you need to go through the objects
in a collection you obtain another iterator, as an iterator is a 'use once' object.
Only the Java collection classes that are sets or lists make iterators available directly. However, as we
will see, a map provides methods to enable the keys or objects, or indeed the key/object pairs, to be
viewed as a set, so an iterator can then be obtained to iterate over the objects in the set view of the map.
The iterator we have seen here is a one-way street - we can go through the objects in a collection one at
a time, and that's it. This is fine for many purposes and is a lot safer than a hand coded loop, as there's
no possibility of getting the boundary conditions wrong. However, if this is not enough, and there will
be times when it isn't, there's another kind of iterator that is more flexible.
List Iterators
The
ListIterator
interface declares methods that you can use to traverse a collection of objects
backwards or forwards. You don't have to elect for a particular direction either. You can change from
forwards to backwards and
vice versa
, so an object can be retrieved more than once.
The
ListIterator
interface extends the
Iterator
interface so the iterator methods you have seen still
apply. The methods defined in the
ListIterator
interface that you use to traverse the list of objects are: