Sunday, May 15, 2011

Difference between Enumeration and Iterator interface or Enumeration vs Iterator

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

Enumeration Iterator
Enumeration contains 2 methods namely hasMoreElements() & nextElement(). Iterator contains three methods namely hasNext(), next(),remove().
No such operation supported. It acts as read-only interface, as delete not supported. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects.
Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.

No comments:

Post a Comment