应该让 equals() 和 hashCode() 返回相同的结果吗?

huangapple go评论65阅读模式
英文:

Should equals() and hashCode() return same result?

问题

相同的结果是指,如果两个元素的 equal() 结果相等,我是否有义务让它们的 hashCode() 也相同?
如果我不这样做会有什么问题呢?

我脑海中首先想到的是,在 ArrayList 中两个元素可能是“相等的”,但在 HashSet 中却不是。允许这种行为是否是不良做法?除了在它们中使用 contains() 方法之外,还可能引起哪些问题呢?

英文:

By same result I mean, if two elements are equal(), am I obliged to make them have same hashCode() as well?
What can go wrong if I don't do that?

First thing that came up to my mind is that 2 elements could be 'equal' in ArrayList, but not in HashSet. Is it bad practice to allow such behavior? And what problems could it make other than using contains() in them?

答案1

得分: 1

如果两个对象根据equals(Object)方法是相等的,那么在这两个对象上调用hashCode方法必须会产生相同的整数结果。

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#hashCode()

可能出现什么问题呢?因为哈希码比较可以比完整对象比较更快,通常只有在哈希码相等时才会进行完整比较。因此,如果你的hashCode函数有问题,你的相等性判断也会有问题。

英文:

> If two objects are equal according to the equals(Object) method, then
> calling the hashCode method on each of the two objects must produce
> the same integer result.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#hashCode()

What could go wrong? Well, because hash code comparisons can be faster than full object comparisons, often the full comparison only happens if the hash code is equal. Thus, if your hashCode function is broken, your equality will be broken too.

huangapple
  • 本文由 发表于 2020年7月26日 19:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63099672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定