为什么Java中的默认hashcode()不好? [英] Why is the default hashcode() in java bad?

查看:1205
本文介绍了为什么Java中的默认hashcode()不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没有记错,Object()类型的对象的java中的默认hashCode()实现是返回对象的内存地址。当我们创建自己的类时,我读到我们想要重写hashCode(),以便当我们将它们插入到像HashMap()这样的与散列相关的集合中时,它将正常工作。但为什么内存地址不好?

if I remember correctly the default hashCode() implementation in java of an object of type Object() is to return the memory address of the object. When we create our own classes, I read that we want to override hashCode() so that when we insert them into a hash related collection like HashMap() it will work properly. But why is a memory address bad?

当然,我们会偶然发现内存不足,而且会发生碰撞,但唯一一种我认为这是个问题的情况是您正在处理数据的TONS并且只有很少的内存,然后它会开始影响性能,因为java中的哈希相关集合通过链接解决冲突(一个存储桶将链接到解析为相同哈希码/索引的值列表)。

Sure we will EVENTUALLY run out of memory and you'll have collisions, but the only case where I see this being a problem is where you are dealing with TONS of data and have very little memory, and then it would START to affect performance because hash related collections in java resolve collisions by chaining(a bucket will link to a list of values that resolved to the same hashcode/index).

推荐答案

如果每个对象都是唯一的,则默认实现可以正常工作。但是如果你重写equals(),那么你隐含地说,具有不同地址的对象可以相互等价。在这种情况下,您还必须重写hashCode()。

The default implementation works fine if every object is unique. But if you override equals() then you are implicitly saying that objects with different addresses can be equivalent to each other. In that case you have to also override hashCode().

考虑String类。

Think of the String class.

String s1 = new String("foo");
String s2 = new String("foo");

这两个字符串是相等的,所以它们的哈希码必须相等。但它们是具有不同地址的不同对象。

These two strings are equal and so their hash codes must be equal. But they are distinct objects with different addresses.

s1 == s2         // false, different addresses
s1.equals(s2)    // true, same contents

使用它们的地址作为哈希代码将是一个错误。因此,String重写hashCode()以确保相等的字符串具有相同的哈希码。这有助于满足hashCode()的合约,即:
$ b

Using their addresses as hash codes would be an error. Therefore, String overrides hashCode() to ensure that equal strings have equal hash codes. This helps meet hashCode()'s contract, which is:


如果 a.equals(b) code>是真的,然后 a.hashCode()== b.hashCode()

底线:如果您覆盖equals(),那么也会覆盖hashCode()。

Bottom line: If you override equals(), also override hashCode().

这篇关于为什么Java中的默认hashcode()不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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