Sunday, June 15, 2014

Explain the difference between an ITERATOR AND an ENUMERATION INTERFACE

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Iterator actually adds one method that Enumeration doesn’t have: remove ().

What is the exact difference between these two interfaces? Does Enumeration have benefits over using Iterator? If anyone could elaborate, a reference article would be appreciated.

The bottom line is, both Enumeration and Iterator will give successive elements, but Iterator is improved in such a way so the method names are shorter, and has an additional remove method. Here is a side-by-side comparison:
  Enumeration                     Iterator
  ----------------                ----------------
  hasMoreElement()                hasNext()
  nextElement()                   next()
  N/A                             remove()

As also mentioned in the Java API Specifications, for newer programs, Iterator should be preferred over Enumeration, as "Iterator takes the place of Enumeration in the Java collections framework." (From the Iterator specifications.)

Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.

No comments:

Post a Comment