Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

EnumMap — a map with enum keys

EnumMap stores keys from one enum type. The example demonstrates construction, insertion, lookup, size, and iteration in enum declaration order.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

EnumMap<K, V> map = new EnumMap<>(K.class);
map.put(key, value);
map.get(key);
map.size();
map.entrySet();

java.util.EnumMap is a map whose keys belong to one enum type. The EnumMap(Class) constructor creates an empty map; pass, for example, Status.class.

The workflow EnumMap(Class)/put/get/size covers construction and basic access. EnumMap.put stores a value, replacing and returning the previous value. EnumMap.get returns the value or null; use containsKey to distinguish absence from a stored null. size() counts mappings, not enum constants.

EnumMap.entrySet provides a map-backed view of entries. Iteration follows enum declaration order, not insertion order.

Inserting a null key throws NullPointerException; null values are allowed. The map is not synchronized: concurrent access involving modifications requires external synchronization.

Examples

import java.util.EnumMap;

public class Main {
    enum Status { NEW, DONE }

    public static void main(String[] args) {
        EnumMap<Status, Integer> counts = new EnumMap<>(Status.class);
        counts.put(Status.DONE, 2);
        counts.put(Status.NEW, 1);
        counts.put(Status.NEW, 3);

        System.out.println(counts.get(Status.NEW));
        System.out.println(counts.size());
        for (var entry : counts.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }
}

Result

3
2
NEW=3
DONE=2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources