gpt4 book ai didi

java - 在两个变量中的任何一个可以相等的情况下,重写 equals 和 hashcode 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-02 14:37:23 24 4
gpt4 key购买 nike

假设我有以下类(class)

public class DualKey {
int key1;
int key2;
// getters, setters and constructors go here
public void equals(Object obj) {
if (obj == null || ! obj instanceOf DualKey)
return false;
return this.key1 == obj.key1 || this.key1 == obj.key2 || this.key2 == obj.key1 || this.key2 == obj.key2;
}

}

是否可以以保留 equals 和 hashcode 约定的方式覆盖 hashcode?

PS:我意识到定义一个比较器可能会更好,但我正在使用 Spark,其中定义相等的唯一方法是重写 equals 方法。

最佳答案

不,这是不可能的,因为 equals() 实现不满足 Java API 要求:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

具体来说,它是不可传递的。根据您的定义, (1,2) == (2,3)(2,3) == (3,4)(1, 2) != (3,4).

这种非传递性使得不可能实现不平凡的哈希码方法。您唯一能做的就是为每个对象返回相同的数字。这将是一个有效的实现,尽管性能很差。

关于java - 在两个变量中的任何一个可以相等的情况下,重写 equals 和 hashcode 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402812/

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