Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

EnumMap: the Class constructor, put, get, and entrySet

Build a transition map for a single enum type, read and update mappings, and iterate over entries in enum declaration order. Learn when a null lookup means a transition is missing.

Version: Java SE 21

Syntax

java.util.EnumMap<K, V>  // K extends Enum<K>

EnumMap(Class<K> keyType)
V put(K key, V value)
V get(Object key)
Set<Map.Entry<K, V>> entrySet()
boolean containsKey(Object key)  // distinguishes absence from a stored null

EnumMap(Class)/put/get/entrySet covers creating, updating, reading, and iterating over a java.util.EnumMap<K, V>. All keys belong to one enum type K. The EnumMap(Class<K> keyType) constructor takes a class token such as State.class to identify that type at run time. The map starts empty: no entry is created automatically for any constant.

put(K key, V value) adds or replaces a mapping. It returns the old value, or null if the key was absent or previously mapped to null. Null values are allowed, but inserting a null key throws NullPointerException.

get(Object key) returns the mapped value, or null for a missing transition key. A stored null gives the same result, so use containsKey(key) when the distinction matters: true means the mapping exists.

entrySet() returns a Set<Map.Entry<K, V>> backed by the map, not a copy. Its iterator visits existing entries in the order in which their enum keys were declared, not the order in which they were inserted. Removing an entry through the view also removes its mapping from the map.

Examples

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

public class Main {
    enum State { NEW, RUNNING, DONE }

    public static void main(String[] args) {
        EnumMap<State, State> next = new EnumMap<>(State.class);
        next.put(State.RUNNING, State.DONE);
        next.put(State.NEW, State.RUNNING);

        System.out.println("Next from NEW: " + next.get(State.NEW));
        System.out.println("Next from DONE: " + next.get(State.DONE));

        for (Map.Entry<State, State> entry : next.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

Result

Next from NEW: RUNNING
Next from DONE: null
NEW -> RUNNING
RUNNING -> DONE

`RUNNING` is inserted before `NEW`, but the loop prints `NEW` first because of the enum declaration order. No transition is stored for `DONE`, so `get(State.DONE)` returns `null`.

Related lessons

  • Java · Lesson 19 · Advanced · Version: 2

Sources