ConcurrentHashMap 的 Key 和 Value 都不能為 null,而 HashMap 卻可以,你知道這么設(shè)計的原因是什么嗎?

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是可以的

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容