Iterator: It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of remove-ability of an element.
Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework.
Syntax:
// Here "c" is any Collection object. itr is of // type Iterator interface and refers to "c" Iterator itr = c.iterator();
Enumeration: Enumeration (or enum) is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. In Java (from 1.5), enums are represented using the enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of the enum is to define our own data types(Enumerated Data Types).
Syntax:
// A simple enum example where enum is declared // outside any class (Note enum keyword instead of // class keyword) enum Color { RED, GREEN, BLUE; }
Difference between Iterator and Enumeration:
The functionality of Enumeration and the Iterator are same. Using Enumeration you can only traverse and fetch the objects, where as using Iterator we can also add and remove the objects. So Iterator can be useful if you want
to manipulate the list and Enumeration is for read-only access.
Iterator | Enumeration |
---|---|
Iterator is a universal cursor as it is applicable for all the collection classes. | Enumeration is not a universal cursor as it applies only to legacy classes. |
Iterator has the remove() method. | Enumeration does not have the remove() method. |
Iterator can do modifications (e.g using remove() method it removes the element from the Collection during traversal). | Enumeration interface acts as a read only interface, one can not do any modifications to Collection while traversing the elements of the Collection. |
Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet . | Enumeration is a legacy interface which is used for traversing Vector, Hashtable. |