0

If I override the hashCode() method but use non prime number for multiplication, I still get the same hashCodes for two same objects.

If I am correct, if the objects are the same their hash codes should also be the same. Accoding to my previous description this can be achieved even using non prime number. So I wanted to ask, what then, is the point of using prime number like 17 or 31? Why can't I just use non prime number?

domke89
  • 41
  • 6
  • To answer this one would have to explain what a linear congruent generator is and how the choice of multiplier effects the distribution of the results. – Dan D. Feb 28 '19 at 22:53
  • I always find it intriguing when people assume that everyone else is using the same language, environment, ecosystem etc. as they are. The minimum must that should be mentioned in this question is the **language** used. – SomeWittyUsername Mar 01 '19 at 14:42
  • Possible duplicate of [Why use a prime number in hashCode?](https://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode) – user85421 Apr 11 '19 at 19:52

1 Answers1

0

For hash tables to work, it is required that the hash code is the same if two objects are the same. "should be" the same isn't good enough :-) That said, the reason why the hash code is the same even for non prime number is that an algorithm is deterministic. Which is should be. So that part is fine in your implementation.

Why should use use prime numbers: the reason is the reverse case: If two objects are not the same, then it would be great if the hash code also is different. It's not always possible, and if the hash code sometimes is the same, then that's fine. But normally, it should be different. When using prime numbers, it turns out that more often hash codes are different for different objects. The reason why is quite complicated, involves a lot of math. See here for details: Why use a prime number in hashCode?

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132