EnumMap keys are enum constants iterated in their declaration order, while null values are allowed and null keys are not.
Java EnumMap: declaration order and nullable values
Ordering does not follow insertion
The fixture inserts REVIEW before RECEIVED. Iteration still reports RECEIVED first because the enum declaration fixes key order. A REVIEW entry with a null value remains present. containsKey distinguishes that state from an absent mapping; get alone cannot.
The domain still needs a meaning for null. An enum state map can use an explicit marker or Optional-like result instead of an ambiguous null value. Enum collections covers when EnumMap and EnumSet fit.
The key type is part of the instance
Construct the map with the enum class or from a nonempty compatible source. A null key is rejected. This local map is not synchronized and does not provide cross-thread state transitions.
Working program
import java.util.EnumMap;
import java.util.Map;
public class ReceiptStageNotes {
enum Stage { RECEIVED, REVIEW, SENT }
public static void main(String[] args) {
Map<Stage, String> notes = new EnumMap<>(Stage.class);
notes.put(Stage.REVIEW, null);
notes.put(Stage.RECEIVED, "logged");
for (Stage stage : notes.keySet()) System.out.println(stage);
System.out.println("review present=" + notes.containsKey(Stage.REVIEW));
System.out.println("review note=" + notes.get(Stage.REVIEW));
}
}Output
RECEIVED
REVIEW
review present=true
review note=nullCosts and boundaries
EnumMap is specialized for one enum key type; its order is tied to that type's declaration. The example does not establish a persisted state machine or concurrency policy.
Common Mistakes
- Do not expect insertion order.
- Do not interpret get == null as proof of absence.
- Do not insert a null enum key.
Read next
Java enums: finite states without ordinal storage, Java EnumMap and EnumSet: finite-state storage, Java computeIfAbsent: null means no new mapping.
