Iterator vs Enumeration

As all of you know both Iterator and Enumeration are used to traverse Collection objects, in a sequential fashion.  Enumeration can be applied to Vector and HashTable. Iterator can be used with most of the Collection objects.

Differences between Iterator & Enumeration:
Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.

See what happens to this code segment,

Vector <String> aVector = new Vector<String>(); 
aVector.add("I"); 
aVector.add("am"); 
aVector.add("really"); 
aVector.add("good");
Enumeration <String> anEnum = aVector.elements(); 
Iterator <String> anItr  = aVector.iterator();
// Traversal using Iterator 
while(anItr.hasNext()) 
{ 
   if (<someCondition>) 
      // This statement will throw ConcurrentModificationException. 
      // Means, Iterator won't allow object modification while it is 
      // getting traversed. Even in the same thread. 
      aVector.remove(index); 
   
   System.out.println(anItr.next()); 
}
// Traversal using Enumeration 
while(anEnum.hasMoreElements()) 
{ 
   if (<someCondition>) 
      aVector.remove(index); 
   
   System.out.println(anEnum.nextElement()); 
}

But Iterator provides a safer way to remove elements from the underlying collection during the iteration with well-defined semantics. See the implementation of Iterator. But here the remove() is supported by only those implementations of Collection that supports element removal.

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

So the above program part can be re-writen as,

while(anItr.hasNext()) 
{ 
   System.out.println(anItr.next());

   if (<someCondition>) 
      anItr.remove();
   // Note: 
   // Before using anItr.remove(), the Iterator should 
   // point to any of its elements. The remove() removes the 
   // element which the Iterator corrently pointing to.
   // Otherwise it will throw IllegalStateException  

}

Note that Iterator.remove() is the only safe way to modify a collection during iteration. In Enumeration, there is “no safe way” to remove elements from a collection while traversing.

About these ads