简体   繁体   English

为什么哈希图中的空键总是转到第一个存储桶?

[英]Why do null keys in the hashmap always go to the first bucket?

What is the benefit? 有什么好处? And why do we need particular methods for nulls like putForNullKey(V value) , getForNullKey() and similar? 为什么我们需要为null提供特殊方法,例如putForNullKey(V value)getForNullKey()和类似方法? What is the benefit? 有什么好处?

You can't calculate hashCode of a null key, so you have to put all the null keys in the same bucket. 您无法计算null键的hashCode,因此必须将所有null键放在同一存储桶中。 You might as well put them in the first bucket. 您最好将它们放在第一个存储桶中。

And you have specific methods for null keys since their logic is different than non-null keys. 而且,您对空键有特定的方法,因为它们的逻辑不同于非空键。 These methods are private anyway, so it shouldn't matter to the user of the HashMap . 这些方法无论如何都是私有的,因此对HashMap的用户来说无关紧要。 The public API is the same for null and non-null keys. 公共API对于null和non-null键是相同的。

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

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