Difference between Enumeration and Iterator in Java

Upasana | December 30, 2019 | 2 min read | 55 views


Iterator is successor to Enumeration which were part of JDK since 1.0 As suggested by Java Docs, we shall always prefer to use Iterator over Enumeration in newer code.

The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

Key differences

Definition

Enumeration

An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

For example, to print all elements of a Vector<E> v:

for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
   System.out.println(e.nextElement());

Iterator

Iterator interface has four methods: hasNext(), next(), remove() and forEachRemaining(Consumer<? super E> action)

Iterator.java
public interface Iterator<E> {

    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

remove() method

Iterator has a remove() method while Enumeration does not have it. Enumeration interface act as a read only interface with only two methods:

Enumeration.java
public interface Enumeration<E> {
    boolean hasMoreElements();
    E nextElement();
}

So using Enumeration, one can not do any modification to underlying Collection while traversing its elements.

Iterator has remove() method as well as forEachRemaining() method which accepts a functional interface.

It is possible (and perfectly legal) to remove items from an underlying Collection while iterating over it using Iterator interface.

Removing element while iterating over collection
public void removeFromCollection(List<Integer> marksList) {
    Iterator<Integer> marks = marksList.iterator();
    while (marks.hasNext()) {
        Integer mark = marks.next();
        if (mark < 40)
            marks.remove();
    }
}

In-fact you can use shorter version, which does the same thing behind the scene:

public void removeFromCollection(List<Integer> marksList) {
    marksList.removeIf(mark -> mark < 40);
}

Fail-fast vs fail-safe

Iterators returned by classes in java.util package (ArrayList, HashMap, HashSet, etc.) are fail-fast by design. These classes throw ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method. This behavior is not present in Enumeration.

For more information, refer to my other article on fail-fast vs fail-safe iterators

Legacy

Enumeration is a legacy interface which is used for traversing Vector, Hashtable. Iterator on the other hand is modern interface used for all newer collections: ArrayList, LinkedList, HashSet, HashMap, TreeMap and TreeSet.

Preference

Iterator shall always be preferred over Enumeration.


Top articles in this category:
  1. 50 Java Interview Questions for SDET Automation Engineer
  2. Java Program to find Factorial of a number
  3. Junit interview questions for SDET automation engineer
  4. Rest Assured API Testing Interview Questions
  5. Java Coding Problems for SDET Automation Engineer
  6. Comparable & Comparator in Java
  7. Anagrams string checker in Java

Recommended books for interview preparation:

Find more on this topic: