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.

Enumeration is twice as fast as Iterator and uses very less memory.

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

About these ads

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