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);
}
}
As the fields of class A
are still fields in B
that need to be hashed, how do I properly include the hash code of the fields in A
in B.hashCode()
? Any of these?
Objects.hash(bStr) + super.hashCode();
// these generate a StackOverflowError:
Objects.hash(bStr, (A) this);
Objects.hash(bStr, A.class.cast(this));
Java Object hashCode() is a native method and returns the integer hash code value of the object. The general contract of hashCode() method is: Multiple invocations of hashCode() should return the same integer value, unless the object property is modified that is being used in the equals() method.
The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.
Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode();
Java Object hashCode () Method hashCode () is the method of Object class. This method returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.
If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same value.
In the above example, we can call the hashCode () method to get the hash code of the String and ArrayList object. It is because the String and ArrayList class inherit the Object class. In the above example, we can see that two objects obj1 and obj2 are generating the same hash code value.
If two Objects are equal, according to the equals (Object) method, then hashCode () method must produce the same Integer on each of the two Objects. If two Objects are unequal, according to the equals (Object) method, It is not necessary the Integer value produced by hashCode () method on each of the two Objects will be distinct.
I'd probably use
Objects.hash(bStr, super.hashCode())
You definitely want to combine the state you know about with the superclass implementation of hashCode()
, so any solution would want to use bStr
and super.hashCode()
... your original idea of addition would work too, of course - it's just a different way of combining the results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With