I was just exploring different kinds of implementations to the hashCode() method. I opened up the java.lang.Integer class and found this implementation for hashCode():
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
My question is, why can't the implementation be as simple as:
public int hashCode(){
return this.value;
}
What is the need to create an additional static method to pass around the value and return the same? Am I overlooking any important detail here?
That code does look odd when viewed on its own.
But notice that the static method
java.lang.Integer.hashCode
:public
The source code in Java 14 shows no comments to explain why this static method was added. Because the method is
public
, I presume this new static method plays a part in some new feature in Java 8, perhaps related to streams, called elsewhere in the OpenJDK codebase.As noted in the Javadoc, the source code of the existing
Integer::hashCode
instance method was rewritten to call the statichashCode
simply for consistency. This way there is only one place where the hash code is actually being generated. Having only one place is wise for review and maintenance of the codebase.Making
hashCode
static is certainly unusual. The purpose of thehashCode
method is to identify one object of that class to another for use in collections such asHashSet
orHashMap
. Given that we are comparing instances by the method, it makes sense forhashCode
to be an instance method rather than static.The optimizing compiler such as HotSpot or OpenJ9 is likely to inline the
hashCode
method calls, making moot the instance-method versus static-method arrangement in source code.