ConcurrentHashMap 的 Key 和 Value 都不能為 null,而 HashMap 卻可以,你知道這么設(shè)計的原因是什么嗎?TreeMap、Hashtable 等 Map 的 Key 和 Value 是否支持 null 呢?
從ConcurrentHashMap他自己的作者(Doug Lea):
http://cs.oswego.edu/pipermail/concurrency-interest/2006-May/002485.html
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.
ConcurrentMaps(ConcurrentHashMaps,ConcurrentSkipListMaps)不允許使用null的主要原因是,無法容納在非并行映射中幾乎無法容忍的歧義。最主要的是,如果map.get(key)return null,則無法檢測到該鍵是否顯式映射到null該鍵。在非并行映射中,您可以通過進行檢查 map.contains(key),但在并行映射中,兩次調(diào)用之間的映射可能已更改。
hashtable也是線程安全的,所以也是key和value也是不可以null的
treeMap 線程不安全,但是因為需要排序,進行key的compareTo方法,所以key是不能null中,value是可以的