Differences between Iterator & Enumeration:
Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.
See what happens to this code segment,
Vector
aVector.add("I");
aVector.add("am");
aVector.add("really");
aVector.add("good");
Enumeration
Iterator
// Traversal using Iterator
while(anItr.hasNext())
{
if (
// Means, Iterator won't allow object modification while it is
// getting traversed. Even in the same thread.
aVector.remove(index);
System.out.println(anItr.next());
}
// Traversal using Enumeration
while(anEnum.hasMoreElements())
{
if (
System.out.println(anEnum.nextElement());
}
But Iterator provides a safer way to remove elements from the underlying collection during the iteration with well-defined semantics. See the implementation of Iterator. But here the remove() is supported by only those implementations of Collection that supports element removal.
public interface Iterator
{
boolean hasNext();
Object next();
void remove(); // Optional
}
So the above program part can be re-writen as,
while(anItr.hasNext())
{
System.out.println(anItr.next());
if (
// Note:
// Before using anItr.remove(), the Iterator should
// point to any of its elements. The remove() removes the
// element which the Iterator corrently pointing to.
// Otherwise it will throw IllegalStateException
}
Note that Iterator.remove() is the only safe way to modify a collection during iteration. In Enumeration, there is “no safe way” to remove elements from a collection while traversing.