Java hashCode() – How Does the hashCode() Method Work?

hashhashtablejavaobject

I am curious how java generates hash values by using hashCode() method of the Object API ?

Best Answer

The hashCode() of Object is actually a native method and the implementation is actually not pure Java. Now, regarding the how it works, this answer from Tom Hawtin does a great job at explaining it:

Many people will claim that Object.hashCode will return the address of the object representation in memory. In modern implementations objects actually move within memory. Instead an area of the object header is used to store the value, which may be lazily derived from the memory address at the time that the value is first requested.

The whole answer is actually worth the read.

Related Question