Enumeration Vs Iterator in java

 Functionalities of both Iterator & Enumeration interfaces are similar that means both generates a series of all elements of the object which is to have its values iterated that can be traversed one at a time using next() or  nextElement() method. The more powerful newer interface Iterator takes place of the old interface Enumeartion in the Java Collections Framework .

Some of the differences between two interfaces are as follows

1. Iterators allows to safe removal of elements from the collection during the iteration by using remove method of Iterator (not by collection’s remove method). Enumeration does not have remove method.

2. 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.

3. Enumerator interface has been superceded by the Iterator interface in Collections Framework. However, not all libraries / classes like ZipFile, DriverManager, etc.. supports the Iterator interface. Some of the classes that support these interfaces are as follows. Iterators can be used with ArrayList, HashMap, Hashtable, HashSet, CopyOnWriteArraySet, etc.. Enumeration can be used with Vector, Hashtable, Dictionary, ConcurrentHashMap, ZipFile, DriverManager, etc…

4. Method names of Iterators have been improved as given below

 

Sample code to iterate ArrayList using Iterators

List list=new ArrayList();
list.add("item1");
list.add("item2");
Iterator it=list.iterator();
while(it.hasNext())
 System.out.println(it.next()+" ");

Sample code to iterate Vectors using Enumeration.

Vector v=new Vector();
v.add("ele1");
v.add("ele2");
Enumeration elements = v.elements() ;
    while (elements.hasMoreElements()) {
         System.out.println(elements.nextElement());
     }

You may also like

Leave a Reply