Sobes.tech
Middle

What are the differences between Enumeration and Iterator?

sobes.tech AI

Answer from AI

Enumeration is the predecessor of Iterator in Java Collection Framework.

Main differences:

Criterion Enumeration Iterator
Methods hasMoreElements(), nextElement() hasNext(), next(), remove()
Removal capability No Yes (remove())
Fail-fast behavior No Yes (throws ConcurrentModificationException if the collection is modified during iteration)
Applicability Old classes (e.g., Vector, Hashtable) All collections from Java 1.2 and above

Example of using Enumeration:

// import java.util.Enumeration;
// import java.util.Vector;

// Vector<String> vector = new Vector<>();
// vector.add("A");
// vector.add("B");

// Enumeration<String> enumeration = vector.elements();
// while (enumeration.hasMoreElements()) {
//     System.out.println(enumeration.nextElement());
// }
What are the differences between Enumeration and… - sobes.tech