Difference Between Iterator And Enumeration

Difference Between Iterator And Enumeration
The most common interview question in Collections is What is the difference between iterator and enumeration.


Iterator is the interface and found in the java.util package.
It has three methods



Enumeration is also an interface and found in the java.util package. An enumeration is an object that generates elements one at a time. It is used for passing through a collection, usually of unknown size. The traversing of elements can only be done once per creation.
It has following methods


Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn’t.
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.

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.

*Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

int i = 0 is an assignment and creation (2 operations)
i get size, check value of i, and compare (3 operations)
i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
*7/8 operations in total, each time the loop runs through

where an enumeration or iterator uses a while(){}
while(v.hasNext()) has next true or false (1 operation)
while(v.hasMoreElements()) has more true or false (1 operation)
*Only one operation per repeat of this loop

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation