How to ensure hashCode() is consistent with equals()?

It doesn’t say the hashcode for an object has to be completely unique, only that the hashcode for two equal objects returns the same hashcode. It’s entirely legal to have two non-equal objects return the same hashcode. However, the more unique a hashcode distribution is over a set of objects, the better performance you’ll get out of HashMaps and other operations that use the hashCode.

IDEs such as IntelliJ Idea have built-in generators for equals and hashCode that generally do a pretty good job at coming up with “good enough” code for most objects (and probably better than some hand-crafted overly-clever hash functions).

For example, here’s a hashCode function that Idea generates for your People class:

public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    return result;
}

Leave a Comment