fb

Ads

Pages

Difference between Iterator and Enumeration in Java

The object returned by the iterator method deserves special mention. It is an Iterator, which is very similar to an Enumeration, but differs in two respects:
Iterator allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.
 


The first point is important: There was no safe way to remove elements from a collection while traversing it with an Enumeration. The semantics of this operation were ill-defined, and differed from implementation to implementation.
The Iterator interface is shown below:

public interface Iterator {
boolean hasNext();
Object next();
void remove(); // Optional
}


The hasNext method is identical in function to Enumeration.hasMoreElements, and the next method is identical in function to Enumeration.nextElement. The remove method removes from the underlying Collection the last element that was returned by next. The remove method may be called only once per call to next, and throws an exception if this condition is violated. Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. The following snippet shows you how to use an Iterator to filter a Collection, that is, to traverse the collection, removing every element that does not satisfy some condition:


static void filter(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (!cond(i.next()))
i.remove();
}


Two things should be kept in mind when looking at this simple piece of code:
The code is polymorphic: it works for any Collection that supports element removal, regardless of implementation. That's how easy it is to write a polymorphic algorithm under the collections framework!
It would have been impossible to write this using Enumeration instead of Iterator, because there's no safe way to remove an element from a collection while traversing
it with an Enumeration.

0 comments:

Post a Comment