Difference between Iterator and Enumeration in Java with Examples
When working with Java Collections, it's essential to understand the differences between Iterator
and Enumeration
. Both are used for traversing elements within a collection, but they serve different purposes and have varying capabilities.
Iterator
An Iterator
is a versatile tool in Java that allows you to traverse through any type of collection, such as Set
, List
, Queue
, Deque
, and even classes implementing the Map
interface. It provides methods to read and remove elements from a collection during iteration.
Syntax:
// Here, "c" represents any Collection object, and "itr" is an Iterator for "c".
Iterator<String> itr = c.iterator();
Key Features:
- Read Elements: You can access each element in the collection.
- Remove Elements: You can remove elements from the collection while iterating using the
remove()
method. - Fail-Fast: It provides fail-fast behavior, which throws
ConcurrentModificationException
if the collection is structurally modified after the iterator is created (except through the iterator's ownremove()
method).
Example of Iterator
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
ArrayList
namedlist
is created, and elements "Red", "Green", and "Blue" are added to it. - Iterator Creation: An
Iterator
is obtained for theArrayList
using theiterator()
method. - Iteration: The
while
loop 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
Enumeration
is an older interface used for traversing legacy collections such as Vector
and Hashtable
. It allows you to read elements from these collections but does not support modifications.
Syntax:
// A simple example of an Enumeration using a Vector
Enumeration<String> elements = vector.elements();
Key Features:
- Limited to Legacy Collections: It's used with legacy classes like
Vector
andHashtable
. - Read Elements: You can fetch elements, and the
hasMoreElements()
method allows you to check for more elements whilenextElement()
retrieves the next one. - No Modification: The
Enumeration
interface lacks methods for removing or modifying elements during traversal.
Example of Enumeration
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
Vector
namedvector
is created, and elements "Red", "Green", and "Blue" are added to it. - Enumeration Creation: An
Enumeration
is obtained for theVector
using theelements()
method. - Iteration: The
while
loop checks if there are more elements in theVector
usinghasMoreElements()
. ThenextElement()
method retrieves the current element, which is printed. - Vector Content: The content of the
Vector
is printed after the iteration. SinceEnumeration
does not support modification, theVector
remains unchanged.
Difference Between Iterator and Enumeration
Feature | Iterator | Enumeration |
---|---|---|
Supported Collections | Universal, applicable to all collection classes in the Java Collections Framework. | Limited to legacy classes like |
Operations Supported | Supports read and remove operations. | Only supports read operation. |
Methods |
|
|
Fail-Fast Behavior | Provides fail-fast behavior during iteration. | Does not support fail-fast behavior. |
Usage in Modern Collections | Preferred for traversing modern collections like | Obsolete in modern applications; primarily used for legacy collections. |
Conclusion
In Java, both Iterator
and Enumeration
are useful for traversing collections. However, Iterator
is more versatile and should be used when working with modern collections, as it supports both reading and modifying elements while offering fail-fast behavior. Enumeration
, on the other hand, is suited for older collections where only element reading is needed. Understanding these differences will help you choose the right tool for your specific needs.