Override hashcode best practice [duplicate]
Possible Duplicate:
Why does Java's hashCode() in String use 31 as a multiplier?
@Override public int hashC开发者_StackOverflow社区ode() {
int result = 17 + hashDouble(re);
result = 31 * result + hashDouble(im);
return result;
}
This is the code from "Effective Java". Is it widely used in enterprise applications? I am concerned about adding the static values. Or should we define 17 and 31 as final variables in some sort of Utility class and reference them from there?
Also can someone explain what these numbers are for? Is 31 just a prime number chosen randomly?
Yes, I see code like this all the time.
I think there's nothing wrong with this practice, and I don't see any benefit to factoring out the constants into external classes (note that the values clearly must not change while the program is running).
The numbers are primes that likely have been chosen somewhat arbitrarily.
I don't have Effective Java to hand, but I have found the following quote:
The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.
精彩评论