Q10: What is the equals() and hashCode() contract, and why must both be overridden together?

The contract dictates:

  1. If a.equals(b) is true, then a.hashCode() == b.hashCode() MUST be true.
  2. If a.hashCode() == b.hashCode(), a.equals(b) may or may not be true (hash collision). If you override .equals() without .hashCode(), key lookups in hash-based collections (HashMap, HashSet) will fail because duplicate objects resolve to different bucket indices.
Overriding equals and hashCode
public class Person {
    private final int id;
    private final String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person person)) return false;
        return id == person.id && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}
💡 Both methods evaluate the exact same identity fields to satisfy the Java collection contract.
Key Takeaways
  • Equal objects MUST have equal hash codes.
  • Failing to override hashCode() breaks HashMap and HashSet lookups.
Knowledge Check

What happens if two distinct instances return the exact same hashCode() value?