Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default implementation of `hashCode`? [duplicate]

Tags:

java

hashcode

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

like image 772
John Threepwood Avatar asked Feb 28 '13 08:02

John Threepwood


People also ask

What is the default implementation for the hashCode method?

In Java, hashCode() by default is a native method, which means that the method has a modifier 'native', when it is implemented directly in the native code in the JVM. Used to digest all the data stored in an instance of the class into a single hash value i.e., a 32-bit signed integer.

How does the default hashCode () work?

By default the hashCode() returns an integer that represents the internal memory address of the object. Where this comes in handy is in the creation and use of an important computer science data structure called a hash table.

How is the hashCode implemented in object Java?

Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode();

What happens when two objects have same hashCode?

HashCode collisions Whenever two different objects have the same hash code, we call this a collision. A collision is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object.


1 Answers

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

like image 54
default locale Avatar answered Oct 06 '22 13:10

default locale