0

I saw a code that overrides equals() and understandably override hashcode() correspondingly.

 @Override
 public int hashCode() {
 int result = id;
 result = 31 * result + (int) (providerId ^ (providerId >>> 32));
 result = 31 * result + (int) (promotionId ^ (promotionId >>> 32));
 result = 31 * result + (coordinate != null ? coordinate.hashCode() : 0);
 return result;
 }

Can someone please explain why is this hashCode good? Why is it unique to a specific object?

What does >> vs. >>> means? I thought the >> do x bit shifts to the right which is like multiplying by 2.

But what does >>> mean?

asked Nov 25, 2014 at 19:49
2
  • 2
    How do you know it's good? Commented Nov 25, 2014 at 19:53
  • Note that hash functions do not have to be unique per equal object. It must be the case that equal objects have equal hashcodes, but the contrapositive is not true: unequal objects do not have to have unequal hash codes. Consider strings, for example. There are a theoretically infinite number of strings ("a", "aa", "aaa"...), yet only 2^32 different integer values. Since infinity is larger than 2^32, there must be some strings that are unequal yet have the same int hash code. Commented Nov 25, 2014 at 19:55

1 Answer 1

1

Can someone please explain why is this hashCode good? Why is it unique to a specific object?

It's not; essentially no hash code function is. It's just supposed to be rare that two objects have the same hash code, not impossible.

What does >> vs. >>> means? I thought the >> do x bit shifts to the right which is like multiplying by 2.

But what does >>> mean?

It's an unsigned right shift. >> shifts in 1s to the left if the first bit was already 1, >>> shifts in 0s no matter what the original bits were.

answered Nov 25, 2014 at 19:51
2
  • but is this pattern make this hash rare? I try to understand why? how the bits usually look like. Or I shouldn't think that way? Commented Nov 25, 2014 at 19:56
  • The point of hash functions is to mess the bits around as much as possible, the messier, the better. Don't try to work out how the bits in the result look. Commented Nov 25, 2014 at 20:05

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.