Default hashCode() implementation for Java Objects

CuriousMind :

I was trying to understand the hashCode() for Java's Object and saw the following code for Java Object's hashCode() method:

package java.lang;
public class Object {

 // Some more code

 public native int hashCode();

 // Some other code

}

Now, we know that if we create a class it implicitly extends the Object class, and to do this I wrote a sample example:

package com.example.entity;
public class FirstClass {
    private int id;
    private String name;
    // getters and setters
}

So, this class viz: FirstClass would be extending the Object class implicitly.

Main class:

package com.example.app.main;
import com.example.entity.FirstClass;
    public class MainApp {
        public static void main(String[] args) {
             FirstClass fs = new FirstClass();
             fs.setId(1);
             fs.setName("TEST");
             System.out.println("The hasCode for object fs is " + fs.hashCode());
         }
 }

As FirstClass is extending Object class implicitly, hence it would have Object classes' hashCode() method.

I invoked the hashCode() on FirstClass object , and as I haven't overridden the hashCode(), by theory it should invoke Object class's hashCode().

My doubt is:

As Object class don't have any implementation, how is it able to calculate the hash-code for any object?

In my case, when I run the program the hash-code which it returned was 366712642.

Can anyone help me understand this?

Eugene :

Even though there are some answers here stating that the default implementation is "memory" based, this is plain wrong. This is not the case for a lot of years now.

Under java-8, you can do :

java -XX:+PrintFlagsFinal | grep hashCode

To get the exact algorithm that is used (5 being default).

  0 == Lehmer random number generator, 
  1 == "somehow" based on memory address
  2 ==  always 1
  3 ==  increment counter 
  4 == memory based again ("somehow")
  5 == read below

By default (5), it is using Marsaglia XOR-Shift algorithm, that has nothing to do with memory.

This is not very hard to prove, if you do:

 System.out.println(new Object().hashCode());

multiple times, in a new VM all the time - you will get the same value, so Marsaglia XOR-Shift starts with a seed (always the same, unless some other code does not alter it) and works from that.

But even if you switch to some hashCode that is memory based, and Objects potentially move around (Garbage Collector calls), how do you ensure that the same hashCode is taken after GC has moved this object? Hint: indentityHashCode and Object headers.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471601&siteId=1