What is the default implementation of `hashCode`?

JavaHashcode

Java Problem Overview


If one does not override the hashCode method, what is the default implementation of hashCode ?

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn ThreepwoodView Question on Stackoverflow
Solution 1 - Javadefault localeView Answer on Stackoverflow
Solution 2 - Javaf1shView Answer on Stackoverflow
Solution 3 - JavaTheWhiteRabbitView Answer on Stackoverflow