Great follow-up, Stanley! Enumeration
and Iterator
are both used to traverse elements in a collection, but they come from different generations of the Java Collection Framework, and they have key differences in capability, safety, and flexibility.
Let’s compare them clearly:
🧾 1. Definition & Origin
Feature | Enumeration | Iterator |
---|---|---|
Introduced in | JDK 1.0 | JDK 1.2 (with Collection Framework) |
Package | java.util.Enumeration | java.util.Iterator |
Type | Interface for legacy classes | Interface for modern collections |
🔄 2. Used With
Enumeration | Iterator |
---|---|
Legacy classes like: | All modern collections like: |
– Vector | – ArrayList , HashSet , LinkedList |
– Stack | – HashMap , TreeSet , etc. |
– Hashtable |
⚙️ 3. Method Comparison
Feature | Enumeration | Iterator |
---|---|---|
Check next | hasMoreElements() | hasNext() |
Get next | nextElement() | next() |
Remove element | ❌ Not supported | ✅ remove() method supported |
➡️ Iterator is more powerful because it allows element removal during iteration (safely, via iterator.remove()
).
🛡️ 4. Fail-Fast Behavior
Behavior | Enumeration | Iterator |
---|---|---|
Fail-fast? | ❌ No | ✅ Yes (throws ConcurrentModificationException ) |
➡️ Enumeration
is not fail-fast: it doesn’t detect concurrent modifications.
➡️ Iterator
is fail-fast: detects structure changes and fails early.
🧪 Example
✅ Using Enumeration
(old way)
Vector<String> vector = new Vector<>();
vector.add("Java");
vector.add("Python");
Enumeration<String> e = vector.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
✅ Using Iterator
(modern way)
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String val = it.next();
if (val.equals("Python")) {
it.remove(); // ✅ Safe removal
}
}
🔚 Summary Table
Feature | Enumeration | Iterator |
---|---|---|
Legacy vs Modern | Legacy | Modern |
Remove support | ❌ Not supported | ✅ Supported |
Fail-fast | ❌ No | ✅ Yes |
Read-only | Yes | No (read + remove) |
Usage Today | Rare (legacy only) | Standard |
✅ When to use what?
- Use
Enumeration
only when working with legacy classes (Vector
,Hashtable
). - Prefer
Iterator
for modern code — it’s safer, supports removal, and is fail-fast.