简体   繁体   English

Java - 允许null作为HashMap密钥的原因?

[英]Java - Reasons for Allowing null as a HashMap Key?

Why Java decided to allow 'null' as a key in HashMap? 为什么Java决定允许'null'作为HashMap中的键? As we know hashcode() can't be calculated on null value. 我们知道hashcode()不能在null值上计算。 Is there any design consideration for this decision to allow null key in HashMap which is not there in Hashtable(Other than considering as a default value)? 是否有任何设计考虑因为这个决定允许HashMap中的null键在Hashtable中不存在(除了考虑作为默认值)?

From the JDK 1.2 Java Collections API Change Summary (not sure where to find the official version on Oracle's website): JDK 1.2 Java Collections API更改摘要 (不确定在Oracle网站上的官方版本的位置):

Added null-key support to HashMap. 为HashMap添加了空键支持。 This was done for consistency with TreeMap and the late, unlamented ArrayMap, and because customers requested it. 这样做是为了与TreeMap和后期的,没有磨损的ArrayMap保持一致,并且因为客户要求它。 Now all of our general-purpose collection implementations accept null keys, values and elements. 现在我们所有的通用集合实现都接受null键,值和元素。

Joshua Bloch and Doug Lea disagreed on this , and this caused problems for concurrent hash maps . Joshua Bloch和Doug Lea对此持不同意见 ,这导致了并发哈希映射的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM