20

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

7 Answers 7

25

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.

10

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).

3
  • 1
    From the Object.java file (This is **typically** implemented by converting the **internal** address of the object into an integer, but this implementation technique is **not** required by the Java<sup>TM</sup> programming language.) - emphasize mine. Mar 8, 2012 at 1:32
  • Will this hashCode returns different value after the object is moved when GC happens?
    – Jacky
    Nov 27, 2013 at 10:01
  • 3
    The idea that hashCode uses the memory address is a historical artefact stackoverflow.com/questions/36236615/…
    – Raedwald
    Mar 26, 2016 at 17:01
6

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.

4

The Object.hashCode() uses the System.identityHashCode() which is based on an id number for a given object.

3

The HashCode () function has several options for creating a hash code. It sets the JVM startup parameter. Function, which create hashCode() written on C++, and you can see code here

  • HashCode==0: Simply returns random numbers with no relation to where in memory the object is found. As far as I can make out, the global read-write of the seed is not optimal for systems with lots of processors.
  • HashCode==1: Counts up the hash code values, not sure at what value they start, but it seems quite high.
  • HashCode==2: Always returns the exact same identity hash code of 1. This can be used to test code that relies on object identity. The reason why JavaChampionTest returned Kirk's URL in the example above is that all objects were returning the same hash code.
  • HashCode==3: Counts up the hash code values, starting from zero. It does not look to be thread safe, so multiple threads could generate objects with the same hash code.
  • HashCode==4: This seems to have some relation to the memory location at which the object was created.
  • HashCode>=5: This is the default algorithm for Java 8 and has a per-thread seed. It uses Marsaglia's xor-shift scheme to produce pseudo-random numbers.

The information was taken from here

3
  • 2
    How is this an answer to the OP's question? This could have been a comment.
    – Mike
    Mar 7, 2017 at 19:47
  • Why did not my record respond? Mar 7, 2017 at 21:04
  • 1
    This is a much better answer to the question with the edit that you added. Too bad the OP still choose a different path.
    – Mike
    Mar 17, 2017 at 15:07
1

Java does not generate meaningful hashCode for you, it is your job as a programmer to generate a useful hashCode. The default hashCode is just the memory location.

1
  • 3
    Inaccurate - the default hashcode is based on the memory location the first time the method is called for the object; see @Pascal's answer.
    – Stephen C
    Dec 24, 2009 at 23:53
0

The hashCode method outputs a numeric value. The hashcode for an object is always the same if the object doesn't change. It's important to mention, that it's not have to be unique.

Default implementation of hashCode() is given in such a way that it returns the Hash Code number for the object based on the address of the object. JVM automatically generates this unique number based on the address of the object.

If two objects are at same memory location (the same object referred by two reference variable) then hashcode number for both will be same but if two objects reside at different memory location then hashcode number for both object will be different.

You probably asked the question because you need to override the method. But, when to override it?

Default implementation of hashCode() method returns hashcode number (unique identity of object) based on the address of the object. But if my application requires to uniquely identify the objects based on some different parameter (rather than address of the object), then I should override hashCode() method and should give implementation as per the requirement.

An important note from Effective Java about the topic:

enter image description here

For more, check out this Java hashcode example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.