100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

The hashCode() and equals() Contract

The hashCode()/equals() contract explained — why equal objects need equal hash codes and how violating it breaks HashMap and HashSet.

hardQ59 of 226 in Object Oriented Programming Est. time: 6 minsLast updated:
Open Code Lab

Expected Interview Answer

The hashCode()/equals() contract requires that whenever two objects are equal according to equals(), they must return the identical hashCode(), so that hash-based collections like HashMap and HashSet can reliably find objects they have already stored.

The contract has three parts: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(); if a.equals(b) is false, hash codes may or may not differ (collisions are allowed, just not required to be avoided); and hashCode() must remain consistent across multiple calls as long as the object’s equals-relevant fields don’t change. A HashMap locates a bucket using hashCode(), then uses equals() to disambiguate among the (possibly several) entries that landed in that bucket. If equals() is overridden without overriding hashCode() consistently, two equal objects can end up with different hash codes, land in different buckets, and the map will never find one when looking up the other — even though equals() says they’re the same. This is one of the most common real-world Java bugs: an object works fine standalone but silently vanishes from a HashSet or fails as a HashMap key.

  • Guarantees correct lookups and duplicate detection in hash-based collections
  • Prevents silent, hard-to-debug data loss in HashMap/HashSet
  • Clarifies that unequal objects may share a hash code (collisions are fine)
  • Establishes a consistency requirement tied to immutable equals-relevant fields

AI Mentor Explanation

A stadium assigns players to warm-up zones (buckets) by jersey number modulo the number of zones, then within a zone identifies the exact player by full name and team. If two players are truly the same person (equal), they must always be assigned to the same zone by the jersey-number rule — otherwise staff looking for that player in the wrong zone will report them missing even though they’re on the field. Two different players landing in the same zone is fine and expected; that’s a normal collision the exact-name check resolves, not a contract violation.

Step-by-Step Explanation

  1. Step 1

    State the equal-implies-same-hash rule

    If a.equals(b) is true, a.hashCode() must equal b.hashCode() — no exceptions.

  2. Step 2

    Clarify unequal objects may collide

    Different objects can share a hash code; that is a permitted collision, not a violation.

  3. Step 3

    Explain how HashMap uses both

    hashCode() picks the bucket; equals() disambiguates entries within that bucket.

  4. Step 4

    Base hashCode() on the same fields as equals()

    Compute hashCode() only from the immutable fields that equals() compares, to keep them consistent.

What Interviewer Expects

  • Precise statement of the contract: equal objects must have equal hash codes
  • Understanding that unequal objects colliding on hash code is allowed
  • A concrete failure scenario: object silently missing from a HashSet/HashMap
  • Knowledge that hashCode()-relevant fields should be immutable while the object is used as a key

Common Mistakes

  • Overriding equals() but leaving the default identity-based hashCode()
  • Believing unequal hash codes are required for unequal objects
  • Mutating a field used in hashCode() after inserting the object into a HashMap/HashSet
  • Computing hashCode() from different fields than equals() compares

Best Answer (HR Friendly)

The contract says that if two objects are equal, they must produce the same hash code — that’s what lets a HashMap or HashSet actually find an object it already stored. If you override equals() without also overriding hashCode() to match, you get a subtle bug where an object that logically equals another one still can’t be found in a hash-based collection, because it landed in a different bucket.

Code Example

Consistent equals() and hashCode()
import java.util.Objects;

class Employee {
    final String id;
    final String name;

    Employee(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Employee e)) return false;
        return id.equals(e.id); // equality based on id only
    }

    @Override
    public int hashCode() {
        return Objects.hash(id); // MUST use the same field(s) as equals()
    }
}

// Without a matching hashCode(), this lookup could fail:
Set<Employee> set = new HashSet<>();
set.add(new Employee("E1", "Asha"));
boolean found = set.contains(new Employee("E1", "Asha")); // true, because hashCode+equals agree

Follow-up Questions

  • What breaks if you mutate a HashMap key's equals-relevant field after insertion?
  • Why is it safe for two unequal objects to share a hash code?
  • How does a HashMap resolve collisions internally?
  • Why should hashCode() implementations avoid using mutable fields?

MCQ Practice

1. If a.equals(b) returns true, what must be true of their hash codes?

The contract requires equal objects to produce equal hash codes so hash-based lookups work correctly.

2. Can two unequal objects share the same hash code?

Hash collisions between unequal objects are allowed; equals() disambiguates them within the same bucket.

3. What is the most common bug from violating this contract?

Mismatched hashCode() sends equal objects to different buckets, so the collection fails to find them.

Flash Cards

Core rule of the contract?a.equals(b) true implies a.hashCode() == b.hashCode().

Are hash collisions between unequal objects allowed?Yes — collisions are permitted, equals() resolves them.

How does HashMap use both methods?hashCode() picks the bucket; equals() finds the exact entry within it.

Most common violation?Overriding equals() without overriding hashCode() to match.

1 / 4

Continue Learning