ConcurrentHashMap · Topic 5 of 6
No null keys or values
Definition​
ConcurrentHashMap rejects null keys and null values. In a concurrent map, a null returned from get must mean "no such key". If null values were allowed you could not tell the two cases apart without another call that another thread may change.
Example code​
null is rejected on purpose
import java.util.concurrent.ConcurrentHashMap;
class Demo {
public static void main(String[] args) {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
try {
map.put("key", null);
} catch (NullPointerException e) {
System.out.println("null value rejected");
}
try {
map.put(null, "value");
} catch (NullPointerException e) {
System.out.println("null key rejected");
}
// use a clear "empty" marker instead of null
map.put("key", "");
System.out.println(map.get("missing") == null); // null here always means "not in the map"
}
}
// Output:
// null value rejected
// null key rejected
// true
Finished this page? Track your progress (saved only in your browser).