What it is and why to use it
An EnumMap associates values with a known enum key type, such as task status or day of the week. It is a specialised Map implementation designed for enum keys. This makes the domain clearer than a string-key map that accepts arbitrary misspellings.
How it works
The constructor receives the enum’s Class so the map knows its key type even while empty. Iteration follows enum declaration order, not insertion order. Missing keys are still missing mappings; constructing an EnumMap does not create an entry for every constant.
Common mistakes and limitations
EnumMap rejects null keys, although null values are permitted. It is not synchronised. Do not assume a missing enum key automatically has a zero value; initialise it or use getOrDefault.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
Map<Status, Integer> counts = new EnumMap<>(Status.class);Examples
Enum Keys with EnumMap
Complete Main.java example — Java 17 or later, without preview features.
import java.util.EnumMap;
import java.util.Map;
public class Main {
enum Status { TODO, DONE }
public static void main(String[] args) {
Map<Status, Integer> counts = new EnumMap<>(Status.class);
counts.put(Status.DONE, 3);
counts.put(Status.TODO, 2);
System.out.println(counts);
System.out.println(counts.getOrDefault(Status.TODO, 0));
}
}- Status declares TODO before DONE, establishing enum natural order.
- The example inserts DONE first, but the printed map still lists TODO first.
- getOrDefault retrieves the existing TODO count of 2. A dashboard can use enum keys to keep its recognised statuses consistent.
- Expected output: {TODO=2, DONE=3} 2
Best practices
- Use enum types for a fixed domain of named alternatives.
- Use EnumSet when only membership is needed.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification