假设我有两个类(class)
class A {
private String aStr;
@Override
public int hashCode() {
return Objects.hash(aStr);
}
}
和
class B extends A {
private String bStr;
@Override
public int hashCode() {
return Objects.hash(bStr);
}
}
由于 A
类的字段仍然是 B
中需要散列的字段,我如何正确地包含 A 中字段的散列码
在 B.hashCode()
中?这些中的任何一个?
Objects.hash(bStr) + super.hashCode();
// these generate a StackOverflowError:
Objects.hash(bStr, (A) this);
Objects.hash(bStr, A.class.cast(this));
最佳答案
我可能会用
Objects.hash(bStr, super.hashCode())
您肯定希望将您知道的状态与 hashCode()
的父类(super class)实现相结合,因此任何解决方案都需要使用 bStr
和 super。 hashCode()
...当然,您最初的加法想法也行得通 - 它只是组合结果的一种不同方式。
关于java - hashCode() : Objects. hash() 和基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670773/