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?
-
2How do you know it's good?The Paramagnetic Croissant– The Paramagnetic Croissant2014年11月25日 19:53:09 +00:00Commented 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.yshavit– yshavit2014年11月25日 19:55:32 +00:00Commented Nov 25, 2014 at 19:55
1 Answer 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.
-
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?Elad Benda– Elad Benda2014年11月25日 19:56:47 +00:00Commented 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.Louis Wasserman– Louis Wasserman2014年11月25日 20:05:11 +00:00Commented Nov 25, 2014 at 20:05