Saturday, 13 July 2013

Difference between Enumeration and Iterator ? #java #interview

both Iterator and Enumeration provides way to traverse or navigate through entire collection in java

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.


As far Enumeration is older than Iterator so that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference 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.



Conclusion:


Enumeration
Iterator
Older
Introduced in JDK 1.0
Introduced later. 
Method signature
Long
Ex:
hasMoreElement()
nextElement()
Short / descriptive
Ex:
hasNext()
next()

Thread Safe*
Not matched
Matched
Can Remove from data
Not matched ,  it’s read only interface
Matched by calling remove ().

PS:

Thread Safe: it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.

Reference:


 http://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.html#ixzz2Yv8BEYas

No comments:

Post a Comment