Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Just to be clear, you're hashing a 64-bit value into a 32-bit one. Also, a good hash function will produce an even distribution of values (for hopefully obvious reasons!).

You could ignore half the bits, but that would leave you with half the possible values producing one single. So, you want to take all the bits into account somehow when producing the hashcode.

Options for mashing the bits together are: AND, OR, XOR. If you think about it, AND and OR aren't going to produce an even distribution of values at all. XOR does, so it's the only good choice.

hashCode returns an int not long. A good hashCode algorithm tries to have different values for different inputs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top