Difference between Iterator and Enumeration Interface

Posted: November 18, 2011 in Java
Tags: ,

Both Iterator and Enumeration are used to traverse Collection objects, in a sequential fashion.  Enumeration can be applied to Vector and HashTable. Iterator can be used with most of the Collection objects.

The main difference between the two is that Iterator is fail-safe. i.e,  If you are using an iterator to go through a collection you can be sure of no concurrent modifications in the underlying collection which may happen in multi-threaded environments.

Documentations say that Enumeration is twice as fast as Iterator and uses very less memory.  How ?  

Iterator don’t allow a simultaneously navigation and modification on an underlying object. They have a control to see if there are concurrent modifications or so, and hence takes more processing. So Enumeration’s performance is virtually 50% faster than Iterator.

Vector <String> vObj= new Vector<String>();
vObj.add(“I”);
vObj.add(“am”);
vObj.add(“really”);
vObj.add(“good”);
Enumeration<String> e = vObj.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s