Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →
TOPIC 4 OF 6 · 2 MIN READ

The equals and hashCode Contract

If two objects are equal, they must have the same hashCode. Breaking the equals and hashCode contract makes HashMap and HashSet lose your objects, which is why interviewers always ask about it.

What you will learn

  • State the equals and hashCode contract
  • Implement both correctly or use a record
  • Explain what breaks when you override only one

Key concepts

equals contract

Reflexive (a.equals(a)), symmetric, transitive, consistent, and a.equals(null) is false.

hashCode contract

Equal objects must return the same hashCode. Unequal objects may share a hash (a collision), but fewer collisions means faster maps.

Records

A record (Java 16+) generates equals, hashCode and toString from its components, which is the easiest way to get them right for value objects.

Step by step

What goes wrong

Override equals but not hashCode: two equal Employee objects get different default hashes, land in different buckets, and set.contains(copy) returns false. Override hashCode but not equals: same bucket, but the default equals compares references, so they still look different.

Examples

Correct implementation and the record alternative

public final class Employee {
    private final String id;
    private final String email;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Employee other)) return false;
        return id.equals(other.id) && email.equals(other.email);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, email);
    }
}

// Same behaviour in one line
public record EmployeeKey(String id, String email) {}

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Put a mutable object in a HashSet, change a field used in hashCode, then call contains. Explain the result.
  • Explain why JPA entities should not base equals on a generated id that is null before saving.

Interview questions

What interviewers ask next on this topic. Answer out loud first, then open the model answer.

Can two unequal objects have the same hashCode?

Yes, that is a collision and it is allowed. HashMap stores both in the same bucket and uses equals to tell them apart. Only the reverse is forbidden: equal objects with different hashes.

What does the default equals do?

Object.equals compares references, like ==. The default hashCode is usually derived from the object identity, so two separate objects with the same fields are not equal unless you override both.

Summary

Equal objects must share a hashCode; override both together on the same fields, keep keys immutable, and use records for value objects.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus