Learnitweb

Java EnumMap Tutorial

The EnumMap class in Java is a specialized Map implementation designed specifically for use with enum keys. It is part of the java.util package and provides a highly efficient, compact representation of key-value mappings where keys are enums.

Unlike general-purpose maps like HashMap or TreeMap, EnumMap is optimized for enums in both performance and memory usage, making it the preferred choice when the keys are of an enum type.


1. Overview of EnumMap

  • Definition: EnumMap<K extends Enum<K>, V> is a Map implementation optimized for enum keys.
  • Characteristics:
    1. Keys must be enum constants; cannot use null as a key.
    2. Maintains keys in natural order, i.e., the order in which they are declared in the enum.
    3. Implements AbstractMap and Serializable.
    4. Highly memory efficient – internally uses an array to store values.
    5. All operations are O(1) in time complexity.
  • Hierarchy:
java.lang.Object
   -> java.util.AbstractMap<K, V>
       -> java.util.EnumMap<K, V>
  • Key Differences from HashMap:
    • EnumMap is faster and uses less memory for enum keys.
    • Null keys are not allowed, but null values are allowed.
    • Keys are maintained in enum declaration order.

2. Creating an EnumMap

EnumMap provides several constructors for creating maps:

2.1 EnumMap(Class<K> keyType)

Creates an empty EnumMap for the specified enum type.

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY }

EnumMap<Day, String> dayMap = new EnumMap<>(Day.class);
dayMap.put(Day.MONDAY, "Meeting");
dayMap.put(Day.TUESDAY, "Workout");
System.out.println(dayMap); // {MONDAY=Meeting, TUESDAY=Workout}

2.2 EnumMap(EnumMap<K, ? extends V> m)

Creates a new EnumMap initialized with all mappings from another EnumMap.

EnumMap<Day, String> copyMap = new EnumMap<>(dayMap);
System.out.println(copyMap); // {MONDAY=Meeting, TUESDAY=Workout}

2.3 EnumMap(Map<K, ? extends V> m)

Creates an EnumMap initialized with all mappings from another Map, as long as the keys are enums.

Map<Day, String> map = new HashMap<>();
map.put(Day.WEDNESDAY, "Study");
EnumMap<Day, String> enumMap = new EnumMap<>(map);
System.out.println(enumMap); // {WEDNESDAY=Study}

3. Adding and Removing Elements

EnumMap supports standard Map operations like put, remove, get, etc.

EnumMap<Day, String> dayMap = new EnumMap<>(Day.class);
dayMap.put(Day.MONDAY, "Meeting");
dayMap.put(Day.TUESDAY, "Workout");

// Retrieve value
System.out.println(dayMap.get(Day.MONDAY)); // Meeting

// Remove key-value pair
dayMap.remove(Day.TUESDAY);
System.out.println(dayMap); // {MONDAY=Meeting}

// Check existence
System.out.println(dayMap.containsKey(Day.MONDAY)); // true
System.out.println(dayMap.containsValue("Workout")); // false

4. Bulk Operations

EnumMap supports bulk operations:

  • putAll(Map<? extends K, ? extends V> m) – Adds all mappings from another map.
  • clear() – Removes all mappings.
  • keySet() – Returns a set of keys.
  • values() – Returns a collection of values.
  • entrySet() – Returns a set of key-value pairs.
EnumMap<Day, String> dayMap = new EnumMap<>(Day.class);
dayMap.put(Day.MONDAY, "Meeting");
dayMap.put(Day.TUESDAY, "Workout");

Map<Day, String> extraMap = new HashMap<>();
extraMap.put(Day.WEDNESDAY, "Study");

dayMap.putAll(extraMap);
System.out.println(dayMap); // {MONDAY=Meeting, TUESDAY=Workout, WEDNESDAY=Study}

dayMap.clear();
System.out.println(dayMap.isEmpty()); // true

5. Iterating Over EnumMap

EnumMap maintains keys in enum declaration order, so iteration is predictable.

EnumMap<Day, String> dayMap = new EnumMap<>(Day.class);
dayMap.put(Day.MONDAY, "Meeting");
dayMap.put(Day.WEDNESDAY, "Study");
dayMap.put(Day.TUESDAY, "Workout");

// Using entrySet()
for (Map.Entry<Day, String> entry : dayMap.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// Using keySet()
for (Day day : dayMap.keySet()) {
    System.out.println(day + " : " + dayMap.get(day));
}

6. Null Handling

  • Null keys are not allowed:
dayMap.put(null, "Holiday"); // Throws NullPointerException
  • Null values are allowed:
dayMap.put(Day.THURSDAY, null);
System.out.println(dayMap); // {MONDAY=Meeting, TUESDAY=Workout, WEDNESDAY=Study, THURSDAY=null}

7. Performance Characteristics

  1. Memory Efficient: Uses an internal array instead of hash buckets.
  2. Fast Operations: put, get, remove are O(1).
  3. Iteration Order: Follows enum declaration order, not insertion order.
  4. Comparison with HashMap: Faster and more compact when keys are enums.

8. Use Cases of EnumMap

  1. Lookup Tables: Map enum constants to corresponding values efficiently.
enum Status { NEW, IN_PROGRESS, DONE }
EnumMap<Status, String> statusMap = EnumMap.of(Status.NEW, "Not started", Status.DONE, "Completed");
  1. State Machines: Store mappings of enum-based states to actions.
  2. Switch Replacement: Replace large switch statements by mapping enums to behaviors.
  3. Counting or Categorization: Maintain counts or properties for enum constants.
EnumMap<Day, Integer> dayCount = new EnumMap<>(Day.class);
dayCount.put(Day.MONDAY, 5);
dayCount.put(Day.TUESDAY, 10);

9. Summary

EnumMap is a specialized Map for enum keys that provides:

  • High performance and memory efficiency.
  • Keys in natural enum declaration order.
  • Standard Map operations plus predictable iteration order.
  • Null keys not allowed, but null values allowed.
  • Ideal for lookup tables, state machines, and enum-based operations.