I read About System.identityHashCode(Object x). You can not override it because its static method but i can override Object's hashCode method. and also this is mentioned for System.identityHashCode(Object x) in javadoc as :
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().The hash code for the null reference is zero.
but when i am running below code by swapping the object in println method i am getting same result.
public class SherlockGCD {
public int hashCode()
{
return super.hashCode();
}
public static void main(String[] args) {
SherlockGCD sher= new SherlockGCD();
SherlockGCD sher1= new SherlockGCD();
System.out.println(System.identityHashCode(sher));
System.out.println(sher1.hashCode());
}
}
Output is :
31866429
16795905
but if you swap the object as below then also same output
System.out.println(System.identityHashCode(sher1));
System.out.println(sher.hashCode());
Output is :
31866429
16795905
so why output is not reversing as i am changing the object in println method??
but when i am running below code by swapping the object in println method i am getting same result.
You shouldn't compare the results of a hashCode
in one run with the results in a different run. For example, what you may have observed is that identity hash codes are allocated lazily - so whichever object you request the hash code for first gets 31866429 and the next gets 16795905 - on your particular system.
If you reverse the order within a single run you should see consistent results:
System.out.println(System.identityHashCode(sher));
System.out.println(sher1.hashCode());
System.out.println(System.identityHashCode(sher1));
System.out.println(sher.hashCode());
Here lines 1 and 4 of the output should have the same value, and lines 2 and 3 should have the same value.
See more on this question at Stackoverflow