I'm trying to understand the native implementation of the hashCode()
method. What exactly does this method return? Is it a memory address or is it a random value?
No, it is just an identifer. It's a unique value for that object; it need not represent the memory address.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. So no, making it random is a bad idea.
Simply put, hashCode() returns an integer value, generated by a hashing algorithm. Objects that are equal (according to their equals()) must return the same hash code. Different objects do not need to return different hash codes.
.hashCode()
native implementation depends on JVM.
E.g. HotSpot has 6 Object.hashCode()
implementations. You can choose it using -XX:hashCode=n
flag running JVM via command line, where n:
0 – Park-Miller RNG (default)
1 – f(address, global_statement)
2 – constant 1
3 – Serial counter
4 – Object address
5 – Thread-local Xorshift
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