Java.Collections.What is the difference between Enumeration and Iterator.

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

FeatureEnumerationIterator
Introduced inJDK 1.0JDK 1.2 (with Collection Framework)
Packagejava.util.Enumerationjava.util.Iterator
TypeInterface for legacy classesInterface for modern collections

🔄 2. Used With

EnumerationIterator
Legacy classes like:All modern collections like:
VectorArrayList, HashSet, LinkedList
StackHashMap, TreeSet, etc.
Hashtable

⚙️ 3. Method Comparison

FeatureEnumerationIterator
Check nexthasMoreElements()hasNext()
Get nextnextElement()next()
Remove elementNot supportedremove() method supported

➡️ Iterator is more powerful because it allows element removal during iteration (safely, via iterator.remove()).


🛡️ 4. Fail-Fast Behavior

BehaviorEnumerationIterator
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

FeatureEnumerationIterator
Legacy vs ModernLegacyModern
Remove support❌ Not supported✅ Supported
Fail-fast❌ No✅ Yes
Read-onlyYesNo (read + remove)
Usage TodayRare (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.
This entry was posted in Без рубрики. Bookmark the permalink.