Java Reference
In-Depth Information
However, there is an existing loophole: Although the implementor of the
immutable collection must implement add and remove , there is no rule that says
these methods must do anything. Instead, the implementor can simply throw a
run-time UnsupportedOperationException . In doing so, the implementor has tech-
nically implemented the interface, while not really providing add and remove .
By convention, interface methods that document that they are optional
can be implemented in this manner. If the implementation chooses not to
implement an optional method, then it should document that fact. It is up to
the client user of the API to verify that the method is implemented by consult-
ing the documentation, and if the client ignores the documentation and calls
the method anyway, the run-time UnsupportedOperationException is thrown,
signifying a programming error.
Optional methods are somewhat controversial, but they do not represent
any new language additions. They are simply a convention.
We will eventually implement all methods. The most interesting of these
methods is iterator , which is a factory method that creates and returns an
Iterator object. The operations that can be performed by an Iterator are
described in Section 6.3.2.
6.3.2 Iterator interface
As described in Section 6.2, an iterator is an object that allows us to iterate
through all objects in a collection. The technique of using an iterator class was
discussed in the context of read-only vectors in Section 6.2.
The Iterator interface in the Collections API is small and contains only
three methods:
An iterator is an
object that allows
us to iterate
through all objects
in a collection.
boolean hasNext( )
Returns true if there are more items to view in this iteration.
AnyType next( )
Returns a reference to the next object not yet seen by this iterator. The object
becomes seen, and thus advances the iterator.
void remove( )
Removes the last item viewed by next . This can be called only once between
calls to next .
Each collection defines its own implementation of the Iterator interface,
in a class that is invisible to users of the java.util package.
The iterators also expect a stable container. An important problem that
occurs in the design of containers and iterators is to decide what happens if the
state of a container is modified while an iteration is in progress. The Collections
The Iterator inter-
face contains only
three methods:
next , hasNext , and
remove .
 
Search WWH ::




Custom Search