Java hash code generation code often uses prime numbers in its calculations. There are good reasons for this, as explained in Why use a prime number in hashCode? and elsewhere.
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 AutoValue using the specific integer 1000003
instead of some other prime number? If I use IntelliJ to create an overridden hashCode
method, it uses integer 31
. Is there some logical and mathematical reasoning behind using the integer 1000003
to calculate hash codes, rather than some other prime number? A Google search did not give me any answer to this.
Its curious to know what the authors were thinking.
Object.hash
,Arrays.hashCode
andList.hashCode
all use the same implementation with 31 as their prime number. If that's what Java is using, I suspect there's no benefit to 1000003 instead of 31. – Credential*31+
"; "[…] I don't remember the details […] shift things over a golden-ratio fraction of the way. […] I guess I also thought it should be a nice simple number to the human eye. […] the idea of making it bigger was just to eat up all those initial zeros more quickly and get the bits to come back around and interfere with each other." – Credential