问题描述
可能是一个愚蠢的问题,但我不想搞砸了。假设我有两个Java类, Class1
和 Class2
,其中 Class2扩展Class1
。我想在两个类中使用Guava覆盖 Object.hashcode()
。对于超类,我有
Possibly a dumb question, but I don't want to screw this up. Let's say I have two Java classes, Class1
and Class2
, where Class2 extends Class1
. I want to override Object.hashcode()
using Guava for both classes. For the superclass, I've got
@Override
public int hashCode() {
return Objects.hashcode(mField1, mField2);
}
对于Class2,实现hashcode()的正确方法是什么? Class1的考虑?是这样的吗?
For Class2, what's the right way to implement hashcode() that takes the members of Class1 into consideration? Is it like this?
@Override
public int hashcode() {
return Objects.hashcode(super.hashcode(), mField3, mField4);
}
这对我来说是正确的,但我正在寻找一些验证。 Joshua Bloch没有在Effective Java中解决这种情况,而Guava文档也没有解决这个问题。
That SEEMS right to me, but I'm looking for some validation. Joshua Bloch doesn't address this situation in Effective Java, and the Guava docs don't either.
推荐答案
是的,看起来正确。如果您有 Objects.hashCode(f1,f2,f3,f4)
,它将是相同的。如果你看一下实现,它就像 result + = 31 * result + hashcodeOfCurrentObject
。这意味着你的结果将是31 +超级哈希码,它不是完全相同,但不会有问题。
Yes, that looks correct. It would be the same if you had Objects.hashCode(f1, f2, f3, f4)
. If you look at the implementation, it's something like result += 31 * result + hashcodeOfCurrentObject
. Which means that your result will be 31 + the super hashcode, which is not exactly the same, but would not be a problem.
这篇关于将超类合并到Guava Objects.hashcode()实现的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!