1

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.

x80486
  • 6,627
  • 5
  • 52
  • 111
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37
  • https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html: `Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.` – fukanchik Mar 29 '16 at 20:05

2 Answers2

2

You can refer Doug Lea comment:

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

Gaurav
  • 126
  • 7
1

From the documentation you can see:

This class and its views and iterators implement all of the optional methods of the Map and Iterator interfaces.

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

This class is a member of the Java Collections Framework.

x80486
  • 6,627
  • 5
  • 52
  • 111