gpt4 book ai didi

java - 为什么我不能只比较两个对象的 hashCode 来确定它们是否相等?

转载 作者:行者123 更新时间:2023-12-01 16:58:32 26 4
gpt4 key购买 nike

为什么Eclipse实现的equals方法要比较每个值,直接比较两个对象的hashCode不是更简单吗?

据我所知:

  • hashCode 始终为相同的输入生成相同的哈希
  • 因此,如果两个对象相等,它们应该具有相同的哈希
  • 如果相等的对象具有相同的哈希值,我只需检查哈希值即可确定对象是否相等

编辑:相关问题,如果 equals 实际上不需要 hashCode,为什么在实现 equals 时总是实现 hashCode?

最佳答案

hashCode always generates the same hash for the same input

正确。

So if two objects are equal, they should have the same hash

正确。

If objects that are equal have the same hash, I can just check the hash in order to determine of objects are equal or not

不合逻辑。不相等的对象也可以具有相同的哈希码。这就是哈希码的目的。

Related question, why does one always implement the hashCode when equals is implemented, if the hashCode isn't actually needed for equals?

因为它需要在 HashMap、HashSet 等中进行哈希处理。如果您认为您的对象永远不会被如此使用,请不要覆盖它,祝您好运。

关于java - 为什么我不能只比较两个对象的 hashCode 来确定它们是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com