Course contentsShow
← Java
Lesson 602 of 2,87014. EnumerationsFree lesson

Creating and Using EnumMap

Create EnumMap instances, add entries, and retrieve values using enum constants as keys.

Creating and Using EnumMap

What you'll learn: How to create EnumMap instances, add key-value pairs, and retrieve values using enum constants as keys.


Why EnumMap Exists

EnumMap is a specialized map implementation designed exclusively for enum keys. Think of it like a custom-built filing cabinet where each drawer is labeled with an enum constant—perfectly organized and incredibly efficient for that specific purpose.

Creating an EnumMap

Unlike regular maps, EnumMap requires you to specify the enum class when constructing it:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

// Create an EnumMap
EnumMap<Day, String> schedule = new EnumMap<>(Day.class);

Notice you must pass Day.class to the constructor—the map needs to know which enum type it's working with.

Adding Entries

Use the standard put method to add key-value pairs:

schedule.put(Day.MONDAY, "Team Meeting");
schedule.put(Day.WEDNESDAY, "Code Review");
schedule.put(Day.FRIDAY, "Project Demo");

Retrieving Values

Retrieve values using enum constants as keys:

String activity = schedule.get(Day.MONDAY);  // "Team Meeting"
String noActivity = schedule.get(Day.SATURDAY);  // null (not present)

Full Example

EnumMap<Day, String> schedule = new EnumMap<>(Day.class);

schedule.put(Day.MONDAY, "Team Meeting");
schedule.put(Day.FRIDAY, "Project Demo");

System.out.println(schedule.get(Day.MONDAY));  // Team Meeting
System.out.println(schedule.containsKey(Day.TUESDAY));  // false
System.out.println(schedule.size());  // 2

Why Use EnumMap?

The map maintains keys in their natural enum order and offers excellent performance because it uses a compact array internally (similar to EnumSet's bit vector approach).

Key Takeaway: EnumMap requires the enum class at construction, uses enum constants as keys via put, and retrieves values via get, providing a type-safe and efficient way to map enums to values.