HashCode (): Objects.hash () and base class?
Let's say I have two classes
class A {
private String aStr;
@Override
public int hashCode() {
return Objects.hash(aStr);
}
}
and
class B extends A {
private String bStr;
@Override
public int hashCode() {
return Objects.hash(bStr);
}
}
Since the fields of the class A
are still fields in B
that need to be hashed, how do you properly include the hash code of the fields in A
in B.hashCode()
? Any of them?
Objects.hash(bStr) + super.hashCode();
// these generate a StackOverflowError:
Objects.hash(bStr, (A) this);
Objects.hash(bStr, A.class.cast(this));
source to share
I would use
Objects.hash(bStr, super.hashCode())
You definitely want to combine the state you know about with the superclass implementation hashCode()
, so any solution will want to use bStr
and super.hashCode()
... your original add idea will work too, of course - it's just a different way to combine the results.
source to share