I've been developing in Java with Netbeans for some time now, and there are some things I just rely on working without really questioning how. Among these are the automatically generated hashCode() and equals() methods.
The equals method is straightforward to follow, but I find the hashCode method somewhat enigmatic. I don't understand why it chooses the multipliers and applies the operations it does.
import java.util.Arrays;
import java.util.Objects;
public class Foo {
int id;
String bar;
byte[] things;
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.id;
hash = 89 * hash + Objects.hashCode(this.bar);
hash = 89 * hash + Arrays.hashCode(this.things);
return hash;
}
}
Searching the documentation, this site, and Google for things like "netbeans generate hashcode" turned up nothing that seemed relevant. Is anyone here familiar with what this generation strategy is and why Netbeans uses it?
Edit:
Thanks for the answers so far! Especially due to this answer on the linked SO question, I understand the logic behind using primes in designing a hashCode method much more fully now. However, the other aspect of my question that nobody has really addressed so far is how and why Netbeans chooses the prime numbers that it does for its generated methods. The hash
field and the other multiplier (89
in my example) seem to be different depending on various factors of the class.
For example, if I add a second String
to the class, hashCode() becomes
public int hashCode() {
int hash = 7;
hash = 13 * hash + this.id;
hash = 13 * hash + Objects.hashCode(this.bar);
hash = 13 * hash + Objects.hashCode(this.baz);
hash = 13 * hash + Arrays.hashCode(this.things);
return hash;
}
So, why does Netbeans choose these specific primes, as opposed to any other ones?