What are EnumMap and EnumSet, and why are they faster than HashMap and HashSet?

EnumMap and EnumSet are specialised collections for enum keys and values. Because an enum has a fixed number of constants, each with an ordinal number, EnumMap stores values in a plain array indexed by ordinal, and EnumSet stores membership as bits in a long. That makes them faster and smaller than hash-based collections, and they keep the enum's declaration order.

Key Points: • EnumMap<K, V>: an array of values indexed by key.ordinal(). There is no hashing and no collisions. • EnumSet: a bit vector (RegularEnumSet for up to 64 constants, JumboEnumSet for more). Operations such as contains, add and containsAll are bit operations. • Both iterate in the enum's declaration order. • EnumSet has handy factory methods: of(), range(), allOf(), noneOf() and complementOf(). • Null keys are not allowed in EnumMap, and null elements are not allowed in EnumSet.

Code Example:

import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class EnumCollections {

    enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
    enum Status { NEW, PAID, SHIPPED, DELIVERED, CANCELLED }

    public static void main(String[] args) {
        Set<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
        Set<Day> weekdays = EnumSet.complementOf(EnumSet.copyOf(weekend));
        Set<Day> midWeek = EnumSet.range(Day.TUESDAY, Day.THURSDAY);

        System.out.println("Weekdays: " + weekdays);
        System.out.println("Mid-week: " + midWeek);
        System.out.println("Is FRIDAY a weekend? " + weekend.contains(Day.FRIDAY));

        Map<Status, Integer> orderCounts = new EnumMap<>(Status.class);
        orderCounts.put(Status.DELIVERED, 120);
        orderCounts.put(Status.NEW, 15);
        orderCounts.put(Status.PAID, 40);
        System.out.println("Counts in enum order: " + orderCounts);
    }
}

Output:

Weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY] Mid-week: [TUESDAY, WEDNESDAY, THURSDAY] Is FRIDAY a weekend? false Counts in enum order: {NEW=15, PAID=40, DELIVERED=120}

Good to Know: EnumSet is the modern replacement for bit flags (int constants combined with |). Effective Java recommends it: you get the speed of bit operations with type safety and readable code.

Interview Tip: A concise interview answer is:

"EnumMap stores values in an array indexed by the enum's ordinal, and EnumSet stores membership as bits in a long, so neither needs hashing. That makes them faster and more compact than HashMap and HashSet, and they iterate in declaration order. Whenever my keys or elements are an enum, I use them by default."

Previous question: How do you implement an LRU cache using LinkedHashMap?

Next question: What is CopyOnWriteArrayList, and when should you use it?

More Java Collections interview questions

All Java Collections questions