If the hashCode() method is not overridden, what will be the result of invoking hashCode() on any object in Java?
In HotSpot JVM by default on the first invocation of non-overloaded Object.hashCode
or System.identityHashCode
a random number is generated and stored in the object header. The consequent calls to Object.hashCode
or System.identityHashCode
just extract this value from the header. By default it has nothing in common with object content or object location, just random number. This behavior is controlled by -XX:hashCode=n
HotSpot JVM option which has the following possible values:
1
(for testing/debugging purposes)Note that even if you set -XX:hashCode=4
, the hashCode will not always point to the object address. Object may be moved later, but hashCode will stay the same. Also object addresses are poorly distributed (if your application uses not so much memory, most objects will be located close to each other), so you may end up having unbalanced hash tables if you use this option.