Card 07/ 09
Null Keys: Allowed in HashMap, Refused by TreeMap
Swapping HashMap for TreeMap to get sorted output breaks code that has worked for years.
A HashMap accepts one null key, and a TreeMap throws NullPointerException on the first attempt to put one, because it must compare every key and cannot compare null. Which maps accept null differs by class, not by interface.
Code that has worked for two years throws the first time somebody swaps a HashMap for a TreeMap to get sorted output. The only change was the word after new:
Map<String, Integer> sorted = new TreeMap<>();
sorted.put(null, 1);Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is nullA HashMap treats a null key as a special case and stores it in the first bucket (one of the slots a hash table sorts its entries into). A TreeMap compares each new key against the ones already there, and even the first key against itself, so null fails immediately.
| Class | Null key | Null values |
|---|---|---|
HashMap | One | Any number |
LinkedHashMap | One | Any number |
TreeMap | No: throws | Any number |
ConcurrentHashMap | No: throws | No: throws |
Map.of(...) | No: throws | No: throws |
Keep null out of maps as a habit rather than checking the table each time. A key that might be missing is what getOrDefault is for, and a value that might not exist is what Optional is for.
← → move through sections and cards