Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing hashcode() in java

In the guidelines to write a good hashCode() written in Effective java, the author mentions the following step if the field is long.

If the field is a long, compute (int) (f ^ (f >>> 32)).

I am not able to get why this is done. Why are we doing this ?

like image 648
Vinoth Kumar C M Avatar asked May 11 '26 11:05

Vinoth Kumar C M


2 Answers

In Java, a long is 64-bit, and an int is 32-bit.

So this is simply taking the upper 32 bits, and bitwise-XORing them with the lower 32 bits.

like image 169
Oliver Charlesworth Avatar answered May 14 '26 03:05

Oliver Charlesworth


Because hasCode is 32-bit integer value and long 64-bit. You need hashCode to differ for values with same lower 32-bit for each long and this function should ensure it.

like image 25
viktor Avatar answered May 14 '26 03:05

viktor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!