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 ?

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

0

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

Comments

Your Answer

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.