Difference between Iterator and Enumeration in Java with Examples
Last Updated :
30 Aug, 2024
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 own remove()
method).
Example of Iterator
Java
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);
}
}
OutputIterator Demonstration:
Initial list: [Red, Green, Blue]
Red
Green
Blue
Modified list: [Red, Green]
Explanation:
- ArrayList Initialization: An
ArrayList
named list
is created, and elements "Red", "Green", and "Blue" are added to it. - Iterator Creation: An
Iterator
is obtained for the ArrayList
using the iterator()
method. - Iteration: The
while
loop checks if there are more elements in the list using hasNext()
. The next()
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
and Hashtable
. - Read Elements: You can fetch elements, and the
hasMoreElements()
method allows you to check for more elements while nextElement()
retrieves the next one. - No Modification: The
Enumeration
interface lacks methods for removing or modifying elements during traversal.
Example of Enumeration
Java
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);
}
}
OutputEnumeration Demonstration:
Red
Green
Blue
Vector content: [Red, Green, Blue]
Explanation:
- Vector Initialization: A
Vector
named vector
is created, and elements "Red", "Green", and "Blue" are added to it. - Enumeration Creation: An
Enumeration
is obtained for the Vector
using the elements()
method. - Iteration: The
while
loop checks if there are more elements in the Vector
using hasMoreElements()
. The nextElement()
method retrieves the current element, which is printed. - Vector Content: The content of the
Vector
is printed after the iteration. Since Enumeration
does not support modification, the Vector
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 Vector and Hashtable . |
---|
Operations Supported | Supports read and remove operations. | Only supports read operation. |
---|
Methods | hasNext() , next() , remove() .
| hasMoreElements() , nextElement() .
|
---|
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 HashMap , ArrayList , etc. | 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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read