Java hashCode()方法是对象等式的可靠度量吗? [英] Is Java hashCode() method a reliable measure of object equality?

查看:187
本文介绍了Java hashCode()方法是对象等式的可靠度量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在比较两个相同类型的复杂对象,其中多个字段由自定义对象类型的数据结构组成。假设没有任何自定义对象覆盖了 hashCode()方法,如果我比较对象中每个字段的哈希代码,并且它们将是相同的,我有100%的信心,被比较的对象的内容是相同的?

I am currently working on comparing two complex objects of the same type, with multiple fields consisting of data structures of custom object types. Assuming that none of the custom objects has overriden the hashCode() method, if I compare the hashcodes of every field in the objects, and they will turn out to be the same, do I have a 100% confidence that the content of the compared objects is the same? If not, which method would you recommend to compare two objects, assuming I can't use any external libraries.

推荐答案

绝对不会使用任何外部函数库。您应该使用 hashCode()作为第一遍 - 如果哈希码不同,您可以假设对象不等。如果散列码相同,您应该 调用 equals()来检查完全平等。

Absolutely not. You should only use hashCode() as a first pass - if the hash codes are different, you can assume the objects are unequal. If the hash codes are the same, you should then call equals() to check for full equality.

以这种方式考虑:只有2个 32 可能的散列码。作为示例,有多少可能不同的对象有 String 类型?远远不止于此。因此,至少两个不等于字符串必须共享相同的哈希码。

Think about it this way: there are only 232 possible hash codes. How many possible different objects are there of type String, as an example? Far more than that. Therefore at least two non-equal strings must share the same hash code.

Eric Lippert 很好地介绍了散列码 - 从.NET的角度来看,但原则是同样。

Eric Lippert writes well about hash codes - admittedly from a .NET viewpoint, but the principles are the same.

这篇关于Java hashCode()方法是对象等式的可靠度量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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