Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right way to incorporate superclass into a Guava Objects.hashcode() implementation?

Tags:

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.

like image 893
Andy Dennie Avatar asked Nov 23 '11 20:11

Andy Dennie


People also ask

What does the hashCode () 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.

What is the return type of the hashCode () method in the object class?

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.

When hashCode method is called in Java?

* 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.


1 Answers

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.

like image 117
Bozho Avatar answered Oct 22 '22 13:10

Bozho