What is difference between Enumeration and Iterator in Java

Carvia Tech | August 05, 2019 | 2 min read | 26 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. Java program to check if two strings are anagrams
  4. Calculate Fibonacci Series in Java
  5. Commonly used Http methods in RESTful services
  6. Check if the given number is Armstrong Number in Java
  7. Calculate factorial of a number in Java using recursion



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info