Current versions of Java provide an extended concept of enumeration through the Iterator interface. This takes the place of enumeration in the Collections framework.
The additional functionality is that an iterator allows the caller to remove elements from the underlying collection during the iteration. The Iterator interface is defined by
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
The first two methods are the same as for enumerations, except that
they have shorter names.
The remove method is new. It removes from the collection the element returned by the last call to next. For example, the following removes all elements of the vector v:
Iterator i = v.iterator();
while (i.hasNext()) {
i.next();
i.remove();
}
The remove method may only be called once per call to
next. An implementation must ensure that an
IllegalStateException
is thrown if either (1) the next method has not yet been
called or (2) the remove method has already been called since
the last call to next. You could think of a sequence of
calls to next and remove as defining a string such
as NRNNNRNNRN in an alphabet of two characters N and R. Then a string
is well-formed provided every occurrence of R is immediately preceded
by an occurrence of N. The code in the example above corresponds to
the string NRNR ...NR.
The remove method is optional. An UnsupportedOperationException must be thrown if the Iterator does not support this operation. The view is expressed in the Collections framework that new implementations should consider using Iterator in preference to Enumeration . This is no real restriction, in view of the optionality of remove, and generally we shall follow this advice.