Today's Question:  What weekend projects have you created?        GIVE A SHOUT

Technical Article => Programming =>  Java

Difference between Enumeration and Iterator in java interview question and answer

  http://www.techlabs4      2012-05-01 07:41:52      20,460    0

This tutorial explains about what are the differences between Iterators and Enumeration and similarity of both interface which may be asked in a core java interview. 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() method incase of Iterator and nextElement() method incase of Enumeration. 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();
Iterator it=list.iterator();
System.out.println(" ");

Sample code to iterate Vectors using Enumeration.
Vector v=new Vector();
Enumeration elements = v.elements() ;
while (elements.hasMoreElements()) {

For more details on Enumeration , you can view my ealier post Enumeration in java with example , Use CopyOnWriteArrayList instead of ArrayList for the solution to ConcurrentModificationException

Source :



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


The truth about programmer

By sonic0002