top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain the difference between ITERATOR AND ENUMERATION INTERFACE with example?

0 votes
469 views
Explain the difference between ITERATOR AND ENUMERATION INTERFACE with example?
posted Mar 17, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Different between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while iterator was introduced later. Iterator can be used with Java arraylist, java hashmap keyset and with any other collection classes.
* Another similarity between Iterator and Enumeration in Java is that functionality of Enumeration interface is duplicated by the Iterator interface.

  • Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

  • Also 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. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

answer Mar 17, 2016 by Rajan Paswan
See the following example of the iterator

import java.util.*;
class IteratorDemo {
    public static void main(String args[]) {
        // create an array list
        ArrayList al = new ArrayList();

        // add elements to the array list
        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // use iterator to display contents of al
        System.out.print("Original contents of al: ");

        Iterator itr = al.iterator();
        while(itr.hasNext()) {    
            Object element = itr.next();
            System.out.print(element + " ");
        }
    }
}
...