How does Java's Iterator differ from the older Enumeration, and where does Enumeration still surface in the JDK?
answer
- the Javadoc names only two differences
- one can delete, the other cannot
- shorter names, unrelated types
- fail-fast belongs to the class, not the interface
- older signatures: resources, archives, network interfaces
basics
~20 sIterator took Enumeration's place in Java 1.2, adding an optional remove() and shorter names, hasNext and next. Enumeration survives in Vector, Hashtable, ClassLoader.getResources, ZipFile.entries and SequenceInputStream. Fail-fast is each class's choice, not an interface difference.
solid answer
~40 s`Iterator` took the place of `Enumeration` when the Collections Framework arrived in Java 1.2, and its Javadoc names two differences: an optional `remove()` that deletes the last returned element, and shorter names, `hasNext()` and `next()` against `hasMoreElements()` and `nextElement()`. Fail-fast is not a third difference, because neither interface promises it: `ArrayList`'s iterator is fail-fast and `CopyOnWriteArrayList`'s is not, while `Vector.elements()` has no check and, in the JDK's code, `Collections.enumeration(list)` inherits the list iterator's, which its Javadoc does not state. `Enumeration` still appears in signatures such as `Hashtable.keys()`, `ClassLoader.getResources()`, `ZipFile.entries()`, `NetworkInterface.getNetworkInterfaces()` and the `SequenceInputStream` constructor. To bridge, use `asIterator()` (since Java 9) or `Collections.list()` one way and `Collections.enumeration()` the other.
code
java · 21 linesimport java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
public class FailFastIsPerClass {
public static void main(String[] args) {
Vector<String> vector = new Vector<>(List.of("a", "b", "c"));
Enumeration<String> fromVector = vector.elements();
fromVector.nextElement();
vector.remove("b");
System.out.println(fromVector.nextElement()); // prints c, no exception
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
Enumeration<String> fromList = Collections.enumeration(list);
fromList.nextElement();
list.add("d");
fromList.nextElement(); // throws ConcurrentModificationException
}
}go deeper
Recall the two method pairs and that only Iterator offers remove(). Know that collections hand out iterators today, and that an Enumeration mostly appears when an older API returns one.
Explain that fail-fast comes from the implementing class rather than either interface, with Vector.elements() and Collections.enumeration(list) as opposite cases. Know the bridges: asIterator(), Collections.list() and Collections.enumeration().
When old code changes a Vector or Hashtable during an Enumeration, expect no ConcurrentModificationException: results are undefined, so skipped elements pass silently. Moving the loop to an iterator can turn that into a ConcurrentModificationException, which is a behaviour change to test.
There is little to decide about the old interface itself; the useful call is a policy for new public APIs. Return a stream or collection, take Enumeration only where an existing contract forces it, and leave working callers alone until their code changes anyway.
## Two cursors over a series of elements `Enumeration` (Java 1.0) and `Iterator` (Java 1.2) do the same basic job: they hand your code the elements of a series one at a time, and your code decides when to ask for the next. `Iterator` "takes the place of" `Enumeration` in the Collections Framework, which arrived in 1.2. `Enumeration` was not deprecated, and it gained a method as late as Java 9. | Aspect | `Enumeration<E>` | `Iterator<E>` | |---|---|---| | Any more? | `hasMoreElements()` | `hasNext()` | | Next element | `nextElement()` | `next()` | | At the end | `NoSuchElementException` | `NoSuchElementException` | | Removal | None | Optional `remove()` | | Bulk | None | `forEachRemaining(Consumer)` (Java 1.8) | | Adapter method | `asIterator()` (Java 9) | None | The two are **unrelated types**: neither extends the other, so an `Iterator` cannot be passed where an `Enumeration` is required. Neither is an `Iterable`, so the enhanced `for` accepts neither. ## The two differences the Javadoc names `Iterator`'s Javadoc says iterators differ from enumerations "in two ways": - **Removal.** `remove()` deletes the last element returned from the underlying collection, at most once per `next()`, and calling it at the wrong moment throws `IllegalStateException`. It is optional: the default implementation throws `UnsupportedOperationException`, and so does the iterator of `List.of(...)`. - **Method names.** The framework's design FAQ calls `Enumeration`'s names "unfortunate", because they are long and frequently used, and gives that as the reason `Iterator` does not extend `Enumeration`. ## Fail-fast is not a third difference A common answer is "Iterator is fail-fast and Enumeration is not". That holds for `Vector` and `Hashtable`, whose docs say so, but it is not a property of either interface. `Iterator`'s contract says behaviour is unspecified if the collection changes other than through `remove()`, "unless an overriding class has specified a concurrent modification policy". **Fail-fast** is one such policy, chosen class by class: | Source | Type | After a structural change | |---|---|---| | `ArrayList.iterator()` | `Iterator` | Throws `ConcurrentModificationException`, best effort | | `Vector.iterator()` | `Iterator` | Throws the same, best effort | | `Vector.elements()` | `Enumeration` | No check; results are undefined | | `Hashtable.keys()` | `Enumeration` | No check; results are undefined | | `Collections.enumeration(list)` | `Enumeration` | Undocumented; the JDK's code follows `list.iterator()`, so throws for an `ArrayList` | | `CopyOnWriteArrayList.iterator()` | `Iterator` | Never throws; walks a snapshot | | `ConcurrentHashMap.keys()` | `Enumeration` | Never throws; reflects the table at or since its creation | Its Javadoc states no policy, but in the JDK's code `Collections.enumeration` forwards to a private `Iterator` it holds, so that iterator's check still fires. The practical trap is the reverse case: a loop over `Vector.elements()` that removes from the `Vector` does not throw, and can silently skip an element. How the modification check works is covered with fail-fast iterators. ## Where Enumeration still surfaces It remains in many long-published signatures: - **Older collections:** `Vector.elements()`, `Hashtable.keys()` and `elements()`, `Properties.propertyNames()`. - **`ConcurrentHashMap`:** `keys()` and `elements()`, because the class includes a version of each `Hashtable` method. - **Resources:** `ClassLoader.getResources(String)`, and `ResourceBundle.getKeys()`, an abstract method you implement when subclassing. - **Archives:** `ZipFile.entries()` and `JarFile.entries()`. - **Networking:** `NetworkInterface.getNetworkInterfaces()` and `getInetAddresses()`. - **Security:** `KeyStore.aliases()`. - **As an input:** the `SequenceInputStream(Enumeration)` constructor takes one. - **As a supertype:** `StringTokenizer` implements `Enumeration<Object>`, and its Javadoc calls it a legacy class. Several of these have stream counterparts: `ClassLoader.resources(String)` and `NetworkInterface.networkInterfaces()` from Java 9, `ZipFile.stream()` from Java 1.8. The `Enumeration` Javadoc says new implementations "should consider using" `Iterator` in preference. ## Converting between the two - `e.asIterator()` returns an `Iterator` over the remaining elements. Its `remove()` throws `UnsupportedOperationException` by default, so adapting does not add removal, and using the enumeration afterwards leaves traversal undefined. - `Collections.list(e)` drains the enumeration into a new `ArrayList`, a copy that the enhanced `for` accepts. - `Collections.enumeration(c)` goes the other way, for an API that requires an `Enumeration`. ```java static void printAll(ClassLoader loader) throws IOException { Enumeration<URL> urls = loader.getResources("app.properties"); urls.asIterator().forEachRemaining(System.out::println); } ``` ## What to do in new code - **Prefer the newer form where one exists:** `table.keySet()` over `Hashtable.keys()`, `ZipFile.stream()` over `ZipFile.entries()`. - **Keep `Enumeration` out of new APIs:** return a collection or a stream, which callers can use directly with the enhanced `for` or stream operations. - **When a contract forces one,** as `ResourceBundle.getKeys()` does, build it with `Collections.enumeration(keys)` rather than writing a class. - **Do not change a collection during an enumeration:** if removal is the goal, use the collection's own iterator, or copy with `Collections.list(e)` first.
- Why doesn't Iterator simply extend Enumeration?The Collections Framework's design FAQ gives the names as the reason: `hasMoreElements` and `nextElement` are long and frequently used, and a new framework was the chance to improve them. Supporting both sets in `Iterator` was judged not worthwhile. So the two are unrelated types, and conversion goes through `asIterator()` or `Collections.enumeration()`.
- Can you use an enhanced for loop directly over an Enumeration?No. The enhanced `for` requires an array or an `Iterable`, and `Enumeration` is neither. Use `Collections.list(e)`, which copies the remaining elements into an `ArrayList`, or `e.asIterator()` with a `while` loop or `forEachRemaining`. A lambda such as `Iterable<T> once = e::asIterator` compiles, but it wraps the same enumeration, so treat it as good for one pass.
- Why does ConcurrentHashMap, added in Java 5, still have keys() and elements() that return an Enumeration?Its Javadoc says it obeys the same functional specification as `Hashtable` and includes a version of each `Hashtable` method, which lets it stand in for that class. `Hashtable`'s enumerations give undefined results after a structural change; these reflect the table at some point at or since their creation. Neither kind throws `ConcurrentModificationException`.
- Iterator is fail-fast and Enumeration is not, because the interfaces define it that way.
- Every Iterator must support remove(), since it is a required method of the interface.
- Enumeration is deprecated and no longer appears in current JDK APIs.
- Collections.enumeration(list) can never throw ConcurrentModificationException because it returns an Enumeration.
- asIterator() lets you remove elements from the collection behind an enumeration.
- Iterator extends Enumeration, so an Iterator can be passed wherever an Enumeration is required.
- Iterator
- Java 1.2
- Enumeration
- Java 1.0
- Enumeration.asIterator
- Java 9
Assumes Java 27; Enumeration.asIterator exists since Java 9, and Iterator and Enumeration are unchanged from Java 25.
context
- Iterator (Java SE 27 & JDK 27)docs.oracle.com
- Enumeration (Java SE 27 & JDK 27)docs.oracle.com
- Hashtable (Java SE 27 & JDK 27)docs.oracle.com