Java: Why you should always override hashCode when overriding equals

What could happen if I only override equals?

Let’s illustrate with an example:

class IntBox {
    int i;
    IntBox(int i) { this.i = i; }

    // equals other IntBoxes that store the same int value.
    @Override
    public boolean equals(Object o) {
        IntBox other = (IntBox) o;
        return this.i == other.i;
    }
}

class Main {
    public static void main(String[] args) {
        Set<IntBox> intBoxes = new HashSet<>();
        intBoxes.add(new IntBox(0));
        boolean found = intBoxes.contains(new IntBox(0));
        // found == false
    }
}

What could happen if I only override hashCode?

This will not break the code as above, but may degrade performance.

Put differently: If you don’t override equals any two objects will be considered non-equal. Since Object.hashCode ensures that all objects are distributed as evenly as possible in a hash based collection Object.hashCode is optimal, and overriding it with anything else will worsen the performance.

Comments

Be the first to comment!