how does the hashCode() method of java works?

Java doesn't generate hashCode(), i.e. nothing automatic is happening here. However, Object generates a HashCode based on the memory address of the instance of the object. Most classes (especially if you are going to use it in any of the Collection API) should implement their own HashCode (and by contract their own equals method).


According to Java Platform API documentation, the calculation of hashcode is based on 32-bit internal JVM address of the Object.

It is true that the object moves during execution (AFAIK the only reason is garbage collector). But hashcode does not change.

So when you have an object like this

Person person1 = new Person();
person1.setName("Alex");

Person person2 = new Person();
person2.setName("Alex");

Person person3 = person2;

In this case person1.hashCode will not be equal to person2.hashCode because the memory addresses of these two objects are not the same.

But person2.hashCode will be equal to person3 because they are pointing to the same object.

So if you need to use hashCode method for your objects you must implement it yourself.

By the way String.hashCode implementation is different. It is something like this: (C# syntax)

public int hashCode(String str)
{
  int h = 0;

  for (int i = 0; i < str.Length; i++)
    h = (h * 31) + str[i];

  return h;
}

edit: No overflow check is done here, so the hashCode may be positive or negative.


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.