我的类(class)有两名成员,a 和 b。 class 和 equals 的实现如下:
public static class Test {
protected int a;
protected int b;
public boolean equals(final Object o) {
if (o == this) {
return true;
} else if (o instanceof Test) {
final Test t = (Test) o;
return a == t.a || b == t.b;
}
return false;
}
}
如何编写高效的哈希码函数?
谢谢。
最佳答案
我认为唯一能够通过 equals(Object)
实现满足 equals/hashcode 契约的 hashcode()
方法是返回常量的方法。
和其他人一样,我不明白为什么您想要使用这些语义定义 equals
方法。除此之外,您已将相等性定义为非传递性:
X.equals(Y) && Y.equals(Z) does not imply X.equals(Z)
关于java - equals 中的 or 子句、哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24759860/