r/javahelp • u/ReligionIsAScam_ • May 20 '20
Wouldn't the Eclipse's auto generated hashcode method go above max int value way too quickly?
@Overridepublic int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
result = prime * result + c;
result = prime * result + d;
return result;
}Say a,b,c,d are only above 100, it would already return a number way above the max integer value. Does this hash function only have very limited uses or am I missing something?
19
Upvotes
2
u/[deleted] May 21 '20 edited May 21 '20
Your question has been answered, but I'll go a little further.
Hash functions are typically some combination of multiplications and additions, modulo some range, where the constants should all be coprime with one another (that is to say, they don't share any common multiples). Because an overflow is similar to a modulo, the overflow becomes just part of the design. And if you're curious, yes, 4294967295 (232 - 1, or the full number of values available to a signed int: -2147483648 to 2147483647) is coprime with 31. So it just happily works.
In fact, it's desirable for small inputs to a hash function to overflow, since that means that small changes in the inputs are more likely to change a large number of bits. That's kinda a flaw in Eclipse's auto-gen hash design - 31's a smallish prime. But it's not used for crypto, so no one really cares.