当hashcode()返回零时,对集合实现的影响是什么 [英] what is the impact over Collection implementations when hashcode() returns zero

查看:218
本文介绍了当hashcode()返回零时,对集合实现的影响是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是为了知道,对集合实现类如 hashmap hashset 对象的 hashcode 方法总是返回 0 $ c> demoClass 。我知道它与 putForNullKey 的hashmap或其他类的集合实现有关,但不知道很多细节。我知道对于空对象hascode是 0 所以它有指定的方法为0哈希码。

Ok just for knowledge , what significance it would made on Collection implementation classes like hashmap,hashset etc if the object's hashcode method always returns 0 in a demoClass. I know it has something to do with putForNullKey of hashmap or other classes of Collection implementation, but dont know much in details. I know for null objects the hascode is 0 so it has specfic method for 0 hashcode.

@Override
public int hashCode() {
return 0;
} 


推荐答案

$ c> HashMap , HashSet 和其他依赖 hashCode 的集合非常低效,因为所有元素/条目将添加到相同的bin。

It will make HashMap, HashSet and other collections that rely on hashCode very inefficient, since all elements/entries would be added to the same bin.

方法如 get() containsKey() contains()将使用 O(n)而不是 / code>。

Methods such as get(), containsKey() and contains() would take O(n) instead of O(1).

BTW,答案不是特定于0 hashCode 。任何常量 hashCode 的行为都是一样的。

BTW, the answer is not specific to a 0 hashCode. Any constant hashCode would behave exactly the same.

这篇关于当hashcode()返回零时,对集合实现的影响是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆