Home »
Java programming language
Differences between Enumeration and Iterator in Java
Java Enumeration vs Iterator: Here, we are going to learn what are the differences between Enumeration and Iterator in java? Compare Enumeration v/s Iterator in java? How Enumeration differs from Iterator in java?
Submitted by Preeti Jain, on July 28, 2019
Enumeration vs Iterator in Java
Here, we will see how Enumeration differs from Iterator?
1) Enumeration
Example:
import java.util.*;
class EnumerationClass {
public static void main(String[] args) {
// creating a Vector instance
Vector v = new Vector();
// add few elements by using addElement() of Vector class
v.addElement(10);
v.addElement(20);
v.addElement(30);
v.addElement(40);
v.addElement(50);
// print the vector list
System.out.println(v);
// creating an object of Enumeration
Enumeration en = v.elements();
// loop to check existing more elements
while (en.hasMoreElements()) {
Integer in = (Integer) en.nextElement();
}
System.out.println(v);
}
}
Output
E:\Programs>javac EnumerationClass.java
Note: EnumerationClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
E:\Programs>java EnumerationClass
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
2) Iterator
Example:
import java.util.*;
class IteratorClass {
public static void main(String[] args) {
// Creating a Set interface object
Set set = new HashSet();
// By using add() method to add few elements in set
set.add("Java");
set.add("Python");
set.add("C++");
set.add("Ruby");
set.add("C");
// Creating an object of Iterator interface
Iterator itr = set.iterator();
// loop for traversing an element
while (itr.hasNext()) {
String str = (String) itr.next();
if (str.equals("C"))
itr.remove();
}
// Display elements of Set interface
System.out.println("The final list of Iterator :" + set);
}
}
Output
E:\Programs>javac IteratorClass.java
Note: IteratorClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
E:\Programs>java IteratorClass
The final list of Iterator :[Ruby, Python, C++, Java]