In Java Collections, Iterator and Enumeration are both used to traverse elements of a collection, but they differ in functionality and usage. Enumeration is the older legacy interface, while Iterator is a modern and more powerful replacement introduced in Java 1.2. Understanding both helps in working with different collection APIs effectively.
- Iterator is a modern interface (Java 1.2+) and supports element removal during traversal using remove().
- Enumeration is a legacy interface (Java 1.0) and only supports forward traversal without modification.
Iterator
An Iterator in Java is an interface that provides a standard way to traverse elements of a collection sequentially. It is widely used with Java Collection Framework to access elements one by one in a controlled manner. Iterator also allows safe modification of elements during traversal.
- Provides controlled access to elements one at a time in a forward direction.
- Supports safe removal of elements during iteration using built-in mechanism.
- Works uniformly across different collection types like List, Set, and Queue.
Syntax
Iterator<String> itr = c.iterator(); // c is a Collection object
import java.util.*;
public class Main {
public static void main(String[] args) {
// Print a header for the demonstration
System.out.println("Iterator Demonstration:");
// Create an ArrayList and add elements to it
ArrayList<String> list = new ArrayList<>();
list.add("Red");
list.add("Green");
list.add("Blue");
// Print the initial list
System.out.println("Initial list: " + list);
// Create an Iterator for the ArrayList
Iterator<String> iterator = list.iterator();
// Iterate through the list
while (iterator.hasNext()) {
// Get the next element in the list
String temp = iterator.next();
System.out.println(temp);
// Remove the element "Blue" if found
if ("Blue".equals(temp)) {
iterator.remove();
}
}
// Print the modified list after removing "Blue"
System.out.println("Modified list: " + list);
}
}
Output
Iterator Demonstration: Initial list: [Red, Green, Blue] Red Green Blue Modified list: [Red, Green]
Explanation:
- ArrayList Initialization: An
ArrayListnamedlistis created, and elements "Red", "Green", and "Blue" are added to it. - Iterator Creation: An
Iteratoris obtained for theArrayListusing theiterator()method. - Iteration: The
whileloop checks if there are more elements in the list usinghasNext(). Thenext()method retrieves the current element, which is printed. - Element Removal: If the current element is "Blue", it is removed from the list using the
remove()method. - Modified List: The modified list is printed, showing that "Blue" has been removed.
Enumeration
An Enumeration in Java is a legacy interface used for iterating over older collection classes like Vector and Hashtable. It provides a simple way to access elements sequentially but does not support modifying the collection during traversal. It is mainly used in older Java codebases.
- Designed specifically for legacy classes such as Vector and Hashtable.
- Uses hasMoreElements() and nextElement() methods for sequential access.
- Does not allow element removal or any structural modification while iterating.
Syntax
Enumeration<String> elements = vector.elements(); // vector is a Vector object
import java.util.*;
public class Main {
public static void main(String[] args) {
// Print a header for the demonstration
System.out.println("Enumeration Demonstration:");
// Create a Vector and add elements to it
Vector<String> vector = new Vector<>();
vector.add("Red");
vector.add("Green");
vector.add("Blue");
// Get an Enumeration for the Vector
Enumeration<String> enumeration = vector.elements();
// Iterate through the Vector using Enumeration
while (enumeration.hasMoreElements()) {
// Get the next element in the Vector
String temp = enumeration.nextElement();
System.out.println(temp);
}
// Print the content of the Vector
System.out.println("Vector content: " + vector);
}
}
Output
Enumeration Demonstration: Red Green Blue Vector content: [Red, Green, Blue]
Explanation:
- Vector Initialization: A
Vectornamedvectoris created, and elements "Red", "Green", and "Blue" are added to it. - Enumeration Creation: An
Enumerationis obtained for theVectorusing theelements()method. - Iteration: The
whileloop checks if there are more elements in theVectorusinghasMoreElements(). ThenextElement()method retrieves the current element, which is printed. - Vector Content: The content of the
Vectoris printed after the iteration. SinceEnumerationdoes not support modification, theVectorremains unchanged.
Difference Between Iterator and Enumeration
| Feature | Iterator | Enumeration |
|---|---|---|
| Introduction | Introduced in Java 1.2 (Collection Framework) | Introduced in Java 1.0 (Legacy API) |
| Package | java.util.Iterator | java.util.Enumeration |
| Applicable Collections | Works with all modern collections like List, Set, Queue | Works only with legacy classes like Vector and Hashtable |
| Traversal Direction | Forward traversal only | Forward traversal only |
| Element Access Methods | next() and hasNext() | nextElement() and hasMoreElements() |
| Remove Operation | Supports element removal using remove() | Does not support removal of elements |
| Modification Support | Safe removal during iteration | No modification allowed during iteration |
| Fail-Fast Behavior | Yes (throws ConcurrentModificationException in case of structural modification) | No fail-fast behavior |
| Performance | Slightly more efficient and flexible | Less efficient and outdated |
| Usage Preference | Preferred in modern Java applications | Rarely used, mainly for legacy code |