Enumeration vs. Iterator

Comparison

Don’t be confused between Enum and Enumeration, totally different.

  • With both, you can enumerate(iterate) the elements in a collection of objects, but Enumeration is older, and Iterator is improved one.
  • Main difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn’t.
  • Enumeration is used when ever we want to make Collection objects as Read-only.
  • Iterator is more secure and safe as compared to Enumeration because it does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.

Enumeration

Screen Shot 2016-07-24 at 12.43.58 PM

Example…

public class EnumerationEx{
   public static void main(String[] args){
      Enumeration numEnumeration;
      Vector num = new Vector();
      num.add(100);
      num.add(200);
      num.add(300);

      numEnumeration = num.elements();
      while(numEnumeration.hasMoreElements()){
         System.out.println(numEnumeration.nextElement());
      }
   }
} 

Output…

100
200
300

Iterator

Screen Shot 2016-07-24 at 12.43.27 PM

Example…

public class IteratorEx{
   public static void main(String[] args){
      LinkedList<Integer> list = new LinkedList<Integer>();
      list.add(100);
      list.add(200);
      list.add(300);

      Iterator<Integer> iterator = list.iterator();

      while(iterator.hasNext()){
         Integer tmp = iterator.next();
         System.out.println("Before: "+tmp);
         if(tmp==200)iterator.remove();
      }

      iterator = list.iterator();
      while(iterator.hasNext()){
         System.out.println("After: "+iterator.next());
      }
   }
}

Output…

Before: 100
Before: 200
Before: 300
After: 100
After: 300

Leave A Comment

Your email address will not be published. Required fields are marked *