Showing posts with label Enumeration. Show all posts
Showing posts with label Enumeration. Show all posts

Difference between Iterator and Enumeration in Java?

In our last tutorial we have seen difference between Iterator and ListIterator. In this tutorial we will see about difference between Iterator and Enumeration in Java. Both Iterator and Enumeration are used to traverse elements in the Collection Object. Differences are,
  • Enumeration are introduced in older Java version and Iterator introduced in later version with additional features.
  • By Enumeration allows only traverse through elements, where as by Iterator we can traverse and also we can remove elements from the Collection Object.
  • Iterator is more secure and safe compared to Enumeration since its thread safe and won't allow others threads to modify the elements in Collection Object while some Thread is Iterating. On that case it will give ConcurrentModificationException

Finally we can decide if we are going for Read-only then we can for Enumeration else we can go for Iterator.

Mainly there are two types of Iterator in Java and they fail-fast and fail-safe Iterators. fail-fast iterators are those who throw ConcurrentModificationException if collection Object is modified when other Thread iterating on same Object. Fail-safe Iterator works on copying collection Object and won't work on original Object and its safe compared to fail-fast.    

Lets see example for both Iterator and Enumeration in Java

public class IteratorEnumerationTest {
 public static void main(String[] args) {
  ArrayList<String> myList = new ArrayList<String>();
  Iterator<String> itr = myList.iterator();
  System.out.println("THROUGH ITERATOR : ");
   System.out.print(", ");   
  Vector<String> vec = new Vector<String>(myList);

  Enumeration<String> enu = vec.elements();
  System.out.println("\n\nTHROUGH ENUMERATION : ");
   System.out.print(enu.nextElement()+", ");


one, two, three, four, five, 

one, two, three, four, five,