3

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 ?

asked Nov 9, 2011 at 10:46
1
  • Think for yourself: How "large" is a long and how large is an int? And then think of the binary representation. ;) Commented Nov 9, 2011 at 10:49

4 Answers 4

3

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.

answered Nov 9, 2011 at 10:49
1

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.

answered Nov 9, 2011 at 10:53
1

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.

answered Nov 9, 2011 at 10:57
0

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

answered Nov 9, 2011 at 10:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.