0

A Google search did not give me any answer to this. But I feel there is logic and mathematical reasoning behind using the integer 1000003 to calculate hash codes.

For example, AutoValue will generate the following hash code for a given value class -

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= this.firstName.hashCode();
    h *= 1000003;
    h ^= this.lastName.hashCode();
    h *= 1000003;
    h ^= this.age;
    return h;
  }

What is the reason behind this specific integer? If I use IntelliJ to create an overridden hashcode method, it uses integer 31.

Its curious to know what the authors were thinking.

Note that Why use a prime number in hashCode? is a similar question. However, that is asking about prime numbers in hash codes in general, whereas this is asking why the specific value 1000003 is used by AutoValue (as opposed to e.g. a different prime number).

M. Justin
  • 9,474
  • 3
  • 68
  • 98
ARK
  • 3,046
  • 2
  • 25
  • 29
  • 1
    Im pretty sure 10^6+3 is a prime, which makes it less likely for a hash collision to happen than a composite number. – sunny-lan Jun 27 '18 at 23:23
  • 1
    A prime number is needed to avoid hash collisions as @AJC mentions. My guess is someone might have decided to "use the 1st prime number over a million" for possibly arbitrary reasons. It would be interesting to know if there is a deeper reason. – tune5ths Jun 27 '18 at 23:36
  • yeah, that seems like a googly thing to do.. – ARK Jun 27 '18 at 23:45

0 Answers0