Difference between Enumeration
and Iterator
can be summarized with the help of following points:
Enumeration
is a legacy interface used to traverse only the legacy classes likeVector
andHashTable
.Iterator
is not a legacy interface.Iterator
can be used for the traversal of collections like HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet etc.Enumeration
has read-only access to the elements in the collection. On the other side,Iterator
can remove the elements from the collection.Enumeration
is not a universal cursor as it applies only to legacy classes.Iterator
is a universal cursor as it is applicable for all the collection classes.Enumeration
was added to the jdk1.0 version whileIterator
was added in jdk1.2 version.Enumeration
is fail-safe in nature. It does not throwConcurrentModificationException
if collection is modified during the traversal. Iterator is fail-fast in nature. It throwsConcurrentModificationException
if a collection is modified while iterating other than its ownremove()
method.Enumeration
has methodshasMoreElements()
andnextElement()
.Iterator
has methodshasNext()
,next()
andremove()
.
Both Iterator
and Enumeration
are available in java.util
package. Both Iterator and Enumerations are unidirectional forward access cursor.
According to Java API Docs, Iterator is always preferred over the Enumeration.
NOTE: The functionality of this interface is duplicated by the Iterator
interface. In addition, Iterator
adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator
in preference to Enumeration
.