Video in progress
Can you put a null key or a null value into a HashMap?
Yes. HashMap accepts one null key and any number of null values. TreeMap (with natural ordering), ConcurrentHashMap and Map.of do not accept null.
📖 Answer
HashMap treats the hash of a null key as 0 and puts it into bucket 0.
Map<String, String> m = new HashMap<>();
m.put(null, "bo'sh");
m.put("a", null);
m.get("a"); // null
m.get("b"); // null — you can't tell the difference!
m.containsKey("a"); // true
Here is the trap: when get() returns null, you can't tell whether the key is missing or its value is null. That is why you use containsKey or getOrDefault.
The others:
TreeMap: with anullkey it callscompareToand throws an NPE (unless the comparator handles it explicitly);ConcurrentHashMap: neither the key nor the value can benull, to remove the ambiguity above in a multithreaded setting;Map.of(...): throws an NPE right away if you passnull.
In practice, the cleanest approach is not to store null values in a map at all.
Sign up to mark studied questions and save your progress.