I have learned that the java object header contains the information such as hashcode、gc year、biased lock and so on. Then a puzzle come to me and in order express my question explicitly. I give an example.
Here is the code:
public class Demo{
@Override
public int hashCode(){
System.out.println("the hashCode method was called");
return super.hashCode();
}
public static void main(String[] args){
Demo demo = new Demo();
System.out.println("after generate an object");
//
Set<Demo> set = new HashSet<Demo>();
set.add(demo);
}
}
And the output:
after generate an object
the hashCode method was called
I guess when we new an object the jvm will set hashcode in object header. But if this in order to generate hashCode it should be invoke hashCode method of this object. However according to the output which seemed it havent invoke hashCode method when new an object. And add value into hashSet the hashCode method is invoked, this as was expected.
So my question is that: When does the jvm assign hashcode value in the object header? It happened in the phase when new an object?
hashCode
method to initialize object's identity hashCode. It works the other way round: Object.hashCode
and System.identityHashCode
call JVM to compute or to extract previously computed identity hashCode.Object.hashCode
or System.identityHashCode
and stores it in the object header. The subsequent calls simply extract the previously computed value from the header.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With