What is EnumMap, how is it implemented, and why is it preferred over HashMap for enum keys?
answer
- Array indexed by ordinal() -> no hashing
- Keys = one enum type, fixed at construction
- Iteration in enum declaration order
- put(null, v) throws NPE; null values OK
- One slot per constant; likely faster than HashMap
basics
~20 sEnumMap is a special map whose keys must be values of one enum type. Internally it's just an array indexed by each enum's position, so it's very fast and compact, and it keeps entries in the enum's declared order.
solid answer
~50 sEnumMap is a high-performance Map implementation specialized for keys from a single enum type, declared as new EnumMap<>(MyEnum.class). Internally it is backed by a plain array sized to the number of enum constants, indexed by each key's ordinal() (its position in the enum declaration). That means no hashing and no collisions — lookups and inserts are constant-time array accesses, likely, though not guaranteed, faster than a HashMap, and smaller unless a large enum has few keys mapped. Iteration order is the natural (declaration) order of the enum constants, which is deterministic. Inserting a null key throws NullPointerException, while get and remove with null just find nothing; null values are allowed. It is not thread-safe, and its iterators are weakly consistent, never throwing ConcurrentModificationException. Prefer EnumMap over HashMap for enum keys: it is compact, likely faster, and predictably ordered. All keys must belong to the same enum type, fixed at construction.
code
java · 14 linesenum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
EnumMap<Day, String> plan = new EnumMap<>(Day.class);
plan.put(Day.WED, "gym");
plan.put(Day.MON, "meeting");
// Iteration is in declaration order, not insertion order:
for (var e : plan.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
// prints MON -> meeting, then WED -> gym
// plan.put(null, "x"); // throws NullPointerException (null key)
plan.put(Day.FRI, null); // null VALUE is allowedgo deeper
Knows EnumMap is a map for enum keys and is usually more efficient than HashMap there.
Explains the ordinal-indexed array implementation, declaration-order iteration, null-key rejection, and that it should be preferred for enum keys.
Discusses the no-hash/no-collision performance and usual memory wins, the single-enum-type constraint fixed at construction, null-value sentinel handling, and thread-safety.
Reasons about when ordinal-indexing assumptions matter (enum evolution, ordinal stability), EnumMap/EnumSet as performance idioms, and API design favoring enum-keyed structures over string-keyed maps.
## What an enum is An **enum** (enumerated type) is a class with a fixed, known set of named constant instances, e.g.: ``` enum Day { MON, TUE, WED, THU, FRI, SAT, SUN } ``` Each constant has an **ordinal**: its zero-based position in the declaration. `Day.MON.ordinal()` is `0`, `Day.TUE.ordinal()` is `1`, and so on; the Javadoc of `Enum.ordinal()` names `EnumMap` among the structures that method exists for. Crucially, the JVM knows *exactly how many* constants an enum has and that the set never changes at runtime. ## The problem EnumMap solves If you use a `HashMap<Day, X>`, the map must hash each key, find a bucket, handle collisions, and allocate a node per entry — general machinery that ignores the fact that enum keys are a small, fixed, densely-numbered set. That's wasteful when you already know each key maps cleanly to an index `0..n-1`. ## How EnumMap works internally `EnumMap` is **array-backed**. When you write `new EnumMap<>(Day.class)`, it: 1. Asks the enum class for its constants and allocates a **plain `Object[]` of exactly that length** (7 for `Day`). 2. To `put(key, value)`, it stores `value` at `array[key.ordinal()]`. To `get(key)`, it reads `array[key.ordinal()]`. So every basic operation is a **direct array index** — **no hashing, no collisions, no bucket chains**. This makes it: - **Likely faster** than `HashMap` (array access vs hash+equals). The Javadoc promises constant time for all basic operations and says "likely (though not guaranteed)" for the comparison. - **Usually more memory-compact**: one array with a slot for every constant, mapped or not, vs bucket arrays + node objects. A large enum with few keys mapped can come out bigger than a `HashMap`. - **Deterministically ordered**: iteration follows the **enum's declaration order** (ascending ordinal), always — unlike `HashMap`'s arbitrary order. A sentinel is used to distinguish "slot holds a real null value" from "slot is empty," which is why it can store null **values** while still tracking presence. ## Rules and limits - **Keys must all be from the same enum type**, fixed when you construct it (you pass the `Class` object, or copy a map that implies it). You can't mix enum types: through a raw reference, `put` throws `ClassCastException`. - **Inserting a null key** throws `NullPointerException`, but `get(null)`, `containsKey(null)` and `remove(null)` just find nothing; **null values are allowed**. - **Not thread-safe** — wrap with `Collections.synchronizedMap` if shared. - **Iterators are weakly consistent**: they never throw `ConcurrentModificationException` and may or may not show changes made during iteration, unlike `HashMap`'s fail-fast iterators. - It implements `Map`, so it fits code written against the interface, unless that code puts a null key. ## When to use it **When your map's keys are constants of a single enum and threads don't share it, prefer `EnumMap` over `HashMap`.** It is compact, likely faster, and gives stable ordering. Typical uses: state-machine transition tables, per-enum configuration/counters, mapping enum to handlers. ## Comparison cheat-sheet | | EnumMap | HashMap | |---|---|---| | Key type | one enum type only | any | | Internals | array indexed by ordinal | hash buckets | | Speed | likely faster (direct index) | hashing overhead | | Memory | one slot per constant | buckets + node per entry | | Iteration order | enum declaration order | unspecified | | Null key | `put` throws NPE | one allowed | | Null value | yes | yes | | Iterators | weakly consistent | fail-fast | ## One-line summary EnumMap = "a Map that is secretly an array indexed by `ordinal()`" — the right choice for enum keys: fast, compact, ordered.
- Why is EnumMap likely faster than HashMap for enum keys, and when is it smaller?It stores values in a plain array indexed by the key's ordinal(), so every get/put is a direct array access with no hashing, no collision handling, and no per-entry node objects. HashMap must hash keys, walk buckets, and allocate Entry nodes. The Javadoc says likely, not guaranteed, about speed. The array has a slot per constant, so it is smaller unless a large enum has few keys mapped.
- What ordering does EnumMap iterate in, and can null be used as a key or value?It iterates in the enum's natural (declaration / ascending ordinal) order, deterministically. Inserting a null key throws NullPointerException, while get and remove with null just find nothing; null values are allowed.
HashMap is a coat-check that computes a locker number for each coat. EnumMap is a fixed row of numbered lockers, one per enum constant — you walk straight to your locker, no lookup desk needed.
- Claiming EnumMap uses hashing — it's array-indexed by ordinal.
- Saying iteration order is insertion or arbitrary — it's enum declaration order.
- Thinking it can store a null key (put throws NPE).
- Assuming it's thread-safe.
- Believing you can mix multiple enum types as keys in one EnumMap.
- Expecting fail-fast iterators; they are weakly consistent and never throw ConcurrentModificationException.
- EnumMap
- Java 1.5
context
- EnumMap (Java SE 27 & JDK 27)docs.oracle.com
- Enum (Java SE 27 & JDK 27)docs.oracle.com