Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object.hashCode() - address or random()?

Tags:

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?

like image 928
johnny-b-goode Avatar asked Apr 19 '13 13:04

johnny-b-goode


People also ask

Does hashCode represent address of an object?

No, it is just an identifer. It's a unique value for that object; it need not represent the memory address.

Will the hashCode () method of object class return the address of the object?

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.)

Can we use random numbers in the hashCode () method?

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.

How does hashCode () method work in Java?

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.


1 Answers

.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

like image 190
bsiamionau Avatar answered Oct 03 '22 17:10

bsiamionau