1

Java use int result = result * 31 + C to compute hash value. Just curious why 31 was chosen. As stated in Effective Java: The value 31 was chosen because of it's an odd prime. If it were even and the multiplication overflowed, information would be lost. Because multiplication by 2 is equivalent shifting.

for overflowing, why long type can not be used? Is it a trade-off about hash collision and memory usages?

Julian
  • 119
  • 6
  • Longs also overflow. – shmosel Jun 10 '18 at 09:33
  • Well, because for most uses of a hash code, `int` is quite long enough. – Dawood ibn Kareem Jun 10 '18 at 09:34
  • 2
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) The answer, *"A lot. An absurd amount. More than you think you are capable of. After you have reached the end of your rope and the pain of not having the answer exceeds the vast amount of shame received by posting your question, that's when you can go ahead and ask. Because at that point, you will have done whatever research necessary to make it a good question worth asking!"* –  Jun 10 '18 at 09:38
  • 1
    If that's what it really says, it is drivel. Beyond 2, 'odd prime' is an oxymoron. In any case the purpose of a hashcode isn't to be unique, it is to be limited in range. – user207421 Jun 10 '18 at 09:45
  • @shmosel thanks. I think @Eran’s answer figure it out fro the usage respects. – Julian Jun 10 '18 at 09:46
  • 1
    Actually, mathematicians frequently use the term "odd prime", rather than "prime other than two". It's no surprise to see the phrase in a quality book like _Effective Java_. An _oxymoron_ is something quite different. – Dawood ibn Kareem Jun 10 '18 at 09:58

1 Answers1

6

The most common usage of hashCode() is to compute the index of the bucket into which to add an element/key to a HashSet/HashMap` (or lookup an existing element/key). That index happens to be an array index.

Array indices can only be int, so it would be meaningless for hashCode() to return long. You would have to convert that long to an int anyway.

Eran
  • 387,369
  • 54
  • 702
  • 768