We often store the collection of data. To traverse the collection of data, we need to make use of cursors.
Iterator and Enumeration are both types of cursors that help us in traversing through the collection of data. They belong to the collection framework. Iterator was added in JDK 1.2 version, and Enumeration was added in JDK 1.0 version.
🛡️ Iterator is a universal object that is used to traverse a set of data. The iterator helps in both removing and reading operations. Iterator is an advanced version of Enumerator. It has additional functionality to remove an element from the collection.
🛡️ Any interfaces implemented, such as Set, List, Queue, and Deque, as well as all classes implementing the Map interface, need the use of an iterator whenever we want to enumerate elements. The only cursor provided for the entire collection framework is the iterator.
🧑💻Example of Iterator
import java.util.*;
class Iterator {
private static void REMOVE(Vector vec, String str) {
Iterator itr = vec.iterator();
while (itr.hasNext()) {
String s = (String) itr.next();
if (s.equals(str)) {
itr.remove();
}
}
/* Displaying all the names from the vector */
System.out.println("The names are:");
itr = vec.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
public static void main(String args[]) {
List lst = new ArrayList(Arrays.asList( new String[] {"Hello", "World", "Coding", "Ninjas", "Code", "Studio"}));
Vector vec = new Vector(lst);
REMOVE(vec, "Code");
}
}
You can also try this code with Online Java Compiler
🛡️Enumerator is a user-defined data type, also called an enum. It is mostly used to give integral constants names as names make programmes simpler to read and maintain.
🛡️Enums are represented by the enum data type in Java (as of 1.5). Enums in Java are more capable than those in C/C++. Additionally, variables, methods, and constructors can be added to it in Java. The primary goal of the enum is to define our own data type (Enumerated Data Types).
🧑💻Example of Enumerator
import java.util.*;
class EnumerationSample {
private static void REMOVE(Vector vec, String str) {
Enumeration enm = vec.elements();
while (enm.hasMoreElements()) {
String s = (String) enm.nextElement();
if (s.equals(str)) {
vec.remove(str);
}
}
/* Displaying all the elements from the vec*/
System.out.println("The names are:");
enm = vec.elements();
while (enm.hasMoreElements()) {
System.out.println(enm.nextElement());
}
}
public static void main(String args[]) {
List lst = new ArrayList(Arrays.asList( new String[] {"Hello", "World", "Coding", "Ninjas", "Code", "Studio"}));
Vector vec = new Vector(lst);
REMOVE(vec, "Studio");
}
}
You can also try this code with Online Java Compiler
We can read and remove elements from the collection while traversing them.
With the help of the Enumerator, we can only read the elements while traversing the collection of elements.
Access
Iterator can be used with any class of collection framework.
It can only be used with legacy collection framework classes like vectors and hash tables.
Fail Fast and Fail-Safe
When a thread iterates a collection, any changes to the collection, such as removing elements from the collection, result in a concurrent modification exception.
Enumeration does not throw concurrent modification exceptions as it is Fail-Safe in nature.
Limitation
Iteration is possible only in a forward direction.
We cannot remove elements from the collection of elements using Enumerator.
What is the difference between iterator and enumeration?
The majority of the collection framework's classes, including ArrayList, HashSet, HashMap, LinkedList, etc., employ iterators to perform iterations. Enumeration is designed to be fail-safe. Iterators tend to fail quickly. Due to its fail-safe design, enumeration is not secure or safe. It is the basic difference between iterator and enumeration.
Why is Enumeration fail-safe?
Similar to the CouncurrentHashMap iterator, it produces a duplicate of the collection object to iterate over, ensuring that the iterator is not interrupted if another thread attempts to change the structure of the collection object (by adding or removing an element).
Why is Iterator important in Java?
A Java iterator is an object that is used to iterate through parameters or entries in a collection. It comes from the technical word "iterating" which refers to looping again. An iterator is typically employed in Java to cycle through any collection of objects.
What is the difference between fail-fast and fail-safe?
Fail-Fast systems halt operations as soon as they can, exposing failures right away and ending the entire process. Fail-Safe systems, on the other hand, don't stop an operation when there is a failure. These systems make every effort to minimize failures. Fail-fast and fail-safe are one of the major difference between iterator and enumeration.
Is HashMap a Fail-Fast?
A couple more instances of fail-fast iterators are the ArrayList and HashMap classes. When iterating over a collection that has undergone structural change, fail-safe iterators do not throw any exceptions.
Conclusion
In this article, we discussed the difference between iterator and enumeration. Also, have implemented the code for iterator and enumerator in Java.