HashMap internals · Topic 5 of 6
Null keys and values
Definition​
HashMap allows one null key and any number of null values. TreeMap and ConcurrentHashMap do not allow a null key, and ConcurrentHashMap does not allow null values either, because a null result from get would then be ambiguous.
Example code​
Which maps accept null
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
class Demo {
static void tryPut(String name, Map<String, String> map) {
try {
map.put(null, "value");
System.out.println(name + ": null key accepted");
} catch (NullPointerException e) {
System.out.println(name + ": null key rejected");
}
}
public static void main(String[] args) {
tryPut("HashMap", new HashMap<>());
tryPut("TreeMap", new TreeMap<>());
tryPut("ConcurrentHashMap", new ConcurrentHashMap<>());
Map<String, String> map = new HashMap<>();
map.put("a", null); // a null value is fine here
System.out.println(map.get("a") + " / " + map.containsKey("a"));
}
}
// Output:
// HashMap: null key accepted
// TreeMap: null key rejected
// ConcurrentHashMap: null key rejected
// null / true
Finished this page? Track your progress (saved only in your browser).