Currently I'm working with ConcurrentHashMap
and I'm very familiar with HashMap
, I've expected a similar behaviour to HashMap
, but when I insert a null
key or value, ConcurrentHashMap
throws a NullPointerException
.
I saw their sources, the ConcurrentHashMap
's fragment:
...
public V put(K key, V value) {
return putVal(key, value, false);
}
...
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
....
And the HashMap
's fragment:
...
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
...
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// It Doesn't check null key or value.
....
Why are they so different when they are working with null
keys or values? This doesn't make sense to me.