What is the default implementation of `hashCode`? [duplicate]
Solution 1:
Then this class inherits hashCode
from one of its ancestors. If non of them overrides it, then Object.hashCode is used.
From the docs:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
So default implementation is JVM-specific
Solution 2:
By default, methods that are not overriden are inherited from Object
.
If you look at that method's documentation, the return values are "[...] distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])
". The method in java.lang.Object
is declared as native, which means the implementation is provided by the JVM and may vary depending on your runtime environment.
A small example:
Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
prints (using my jdk6):
1660187542
516992923
A Hex representation of the hashCode()
value is used in the default implementation of toString()
by the way: Running System.out.println(o1)
prints something like
java.lang.Object@7a5e1077
Solution 3:
Object.hashcode() is a native method.
public native int hashCode();
That means it's implemented in platform specific code and is exposed as a native method.
code for the same will be a compiled code and not available withing JDK
this existing question might provide more info.