r/javahelp • • 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

5 comments sorted by

22

u/Doddzi24 May 20 '20

Yes, it can actually overflow multiple times.

The thing is that this doesn't really matter. Each time the hashcode method is called on a distinct object, it will overflow at the exact same point(s) every time, meaning it will still return the same hashcode every time.

4

u/ReligionIsAScam_ May 20 '20

Ah makes a lot of sense, thanks!

7

u/Robyt3 May 20 '20

Aside from your question, which has been answered: You can just use Objects.hash(a, b, c, d); instead of generating the math and prime stuff in most cases.

1

u/ReligionIsAScam_ May 20 '20

Interesting! Appreciated

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.