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?
- If Yes. Why it havent invoke hashcode method, and without this how to calculate hashcode of this object.
- If No. Uhhh... It make no sense that update hashcode in object header every invoke invoke hashCode method.