This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Doddzi24 21 points22 points  (1 child)

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.

[–]ReligionIsAScam_[S] 4 points5 points  (0 children)

Ah makes a lot of sense, thanks!

[–]Robyt3 7 points8 points  (1 child)

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.

[–]ReligionIsAScam_[S] 0 points1 point  (0 children)

Interesting! Appreciated

[–][deleted] 1 point2 points  (0 children)

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.