0Pricing
Java Academy · Lesson

EnumMap

Efficient enum-keyed maps.

What Is EnumMap?

EnumMap is a specialized Map whose keys are constants of a single enum type.

Internally it is backed by a plain array indexed by the constant's ordinal. This makes lookups and inserts extremely fast with no hashing.

import java.util.EnumMap;
import java.util.Map;

public class Main {
    enum Day { MON, TUE, WED }
    public static void main(String[] args) {
        Map<Day, String> plan = new EnumMap<>(Day.class);
        plan.put(Day.MON, "Gym");
        plan.put(Day.WED, "Swim");
        System.out.println(plan);
    }
}

Construction Needs the Class

An EnumMap must know the key type up front, so the constructor takes the Class object: new EnumMap<>(Day.class).

This is how it sizes its internal array to the number of constants.

import java.util.EnumMap;

public class Main {
    enum Priority { LOW, MEDIUM, HIGH }
    public static void main(String[] args) {
        EnumMap<Priority, Integer> counts = new EnumMap<>(Priority.class);
        counts.put(Priority.HIGH, 5);
        System.out.println(counts.get(Priority.HIGH));
    }
}

All lessons in this course

  1. Enums with Fields and Methods
  2. Abstract Methods in Enums
  3. EnumSet
  4. EnumMap
← Back to Java Academy