Monday, 2 May 2016

Why ConcurrentHashMap doesn't allow null keys and null values ?


Reason #1. Purpose of null key
 If map.get(key) returns null, you can't detect whether the key explicitly maps to null or the key isn't mapped.

Reason #2. Ambiguities
In the ConcurrentHashMap implementation, map can be changed in between.

If it supports null key, in below code key k may be deleted in between get and containsKey calls and code will return null instead of KeyNotPresentException (expected)


if (map.containsKey(k)) {
     return map.get(k);
else {
     throw new KeyNotPresentException();
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.