CKTIS / Java
EnumMap: creating, writing, reading, and counting entries
Create an empty EnumMap with Day.class, store and retrieve values, and see why replacing a value for an existing key does not change the number of entries.
Version: Java SE 21
Syntax
import java.util.EnumMap;
EnumMap<Day, String> plan = new EnumMap<>(Day.class);
String previous = plan.put(Day.MON, "Study");
String current = plan.get(Day.MON);
int count = plan.size();java.util.EnumMap<K, V> uses keys from one enum type. The EnumMap(Class) constructor, declared as EnumMap(Class<K> keyType), takes a class object such as Day.class, not a constant such as Day.MON. It creates an empty map without adding entries for the constants. Passing null as keyType throws NullPointerException.
put(K key, V value) adds an entry for a new key or replaces the value for an existing key. It returns the previous value, not the value just stored. A null result means there was no previous entry or the previous value was null. Null values are allowed, but passing a null key to put throws NullPointerException.
get(Object key) reads a value without changing the map. It returns null both for a missing key and for a key explicitly mapped to null. Use containsKey(key) to tell the difference: it returns true if an entry exists, even when its value is null.
size() returns the current entry count as an int, not the number of enum constants. Adding a new key increases the count by one, even if its value is null. Replacing the value for an existing key leaves the count unchanged.
Examples
import java.util.EnumMap;
public class Main {
enum Day { MON, TUE, WED }
public static void main(String[] args) {
EnumMap<Day, String> plan = new EnumMap<>(Day.class);
System.out.println("initial size: " + plan.size());
plan.put(Day.MON, "Study");
System.out.println("after insert: " + plan.size());
System.out.println("previous MON: " + plan.put(Day.MON, "Review"));
System.out.println("current MON: " + plan.get(Day.MON));
System.out.println("after update: " + plan.size());
plan.put(Day.TUE, null);
System.out.println("TUE: " + plan.get(Day.TUE) + ", present: " + plan.containsKey(Day.TUE));
System.out.println("WED: " + plan.get(Day.WED) + ", present: " + plan.containsKey(Day.WED));
System.out.println("final size: " + plan.size());
}
}Result
initial size: 0 after insert: 1 previous MON: Study current MON: Review after update: 1 TUE: null, present: true WED: null, present: false final size: 2
Inserting `MON` gives the map one entry. Updating it returns `Study`, and reading it gives `Review`; the count stays at `1`. `TUE` is mapped to `null` and counts as the second entry, whereas `WED` is absent.
Related lessons
- Java · Lesson 10 · Intermediate · Version: 2