Typically the default implementation of Object.hashCode()
is some function of the allocated address of the object in memory (though this is not mandated by the JLS). Given that the VM shunts objects about in memory, why does the value returned by System.identityHashCode()
never change during the object's lifetime?
If it is a "one-shot" calculation (the object's hashCode
is calculated once and stashed in the object header or something), then does that mean it is possible for two objects to have the same identityHashCode
(if they happen to be first allocated at the same address in memory)?
The java. lang. System. identityHashCode() is the method which is used to return the same hash code for any given object that is returned by the default method hashCode(). Also, for every hash code with a null reference zero is returned.
The hashcode() method is a non-final instance method, and should be overridden in any class where the equals(Object) is overridden. By contrast, identityHashCode(Object) is a static method and therefore cannot be overridden.
Modern JVMs save the value in the object header. I believe the value is typically calculated only on first use in order to keep time spent in object allocation to a minimum (sometimes down to as low as a dozen cycles). The common Sun JVM can be compiled so that the identity hash code is always 1 for all objects.
Multiple objects can have the same identity hash code. That is the nature of hash codes.
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