ConcurrentHashMap
的 JavaDoc是这样说的:
Like
Hashtable
but unlikeHashMap
, this class does not allownull
to be used as a key or value.
我的问题:为什么?
第二个问题:为什么Hashtable
不允许null?
我使用了很多 HashMap 来存储数据。但是当更改为 ConcurrentHashMap
时,由于 NullPointerExceptions,我遇到了几次麻烦。
最佳答案
From the author of ConcurrentHashMap
himself (Doug Lea) :
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)
returnsnull
, you can't detect whether the key explicitly maps tonull
vs the key isn't mapped. In a non-concurrent map, you can check this viamap.contains(key)
, but in a concurrent one, the map might have changed between calls.
关于java - 为什么 ConcurrentHashMap 会阻止 null 键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698638/