具有相同哈希码的两个Java对象不一定相等吗? [英] Are two Java objects with same hashcodes not necessarily equal?

查看:752
本文介绍了具有相同哈希码的两个Java对象不一定相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解为什么为两个相等的对象(通过equals)提供相同的哈希码很重要.但是反之亦然,如果两个对象具有相同的哈希码,它们必须相等吗?合同还存在吗?我找不到一个可能发生这种情况的示例,因为如果所有参与equals方法的属性都被用来覆盖hashcode方法,那么我们将始终对相等的对象使用相同的hashcode.请发表评论.

I understand why providing same hashcode for two equal (through equals) objects is important. But is the vice versa true as well, if two objects have same hashcode do they have to be equal? Does the contract still hold? I cannot find an example where this could happen, because if all those attributes that are taking part in equals method are being used to override hashcode method as well then we will always same hashcode of objects that are equal. Please comment.

推荐答案

如果两个对象具有相同的hashcode,则它们不一定相等.否则,您将发现完美的哈希函数.

If two objects have the same hashcode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function.

但事实恰恰相反:如果对象相等,则它们必须具有相同的hashcode.

But the opposite is true: if the objects are equal, then they must have the same hashcode.

这篇关于具有相同哈希码的两个Java对象不一定相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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