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); }
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); }
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.
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.
hashCode() Method The hashCode() is a method of Java Integer Class which determines the hash code for a given Integer. It overrides hashCode in class Object. By default, this method returns a random integer that is unique for each instance.
* Program Demonstrate hashcode() method of Method Class. Program 2: In this program, after getting a list of Method objects of a class object by calling getMethods() method of class object, hashCode() method of Method object is called for each method object of the list.
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.
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