Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    equals and hashCode: The Contract

    equals decides whether two objects are logically equal (02javaclassesobjectsandmemory.md Ch 9).

    Chapter 8 of 125 min readOften asked in interviews

    The Plain Picture#

    A library files books in numbered bins by a quick rule — say, the first letter of the title. To check "do we have Biology Basics?", the librarian goes straight to bin B and compares titles only there. If two copies of the same book were somehow filed into different bins, the librarian would look in one bin and wrongly say "we don't have it".

    The Real Names#

    • equals decides whether two objects are logically equal (Classes, Objects and Memory Ch 9).

    • hashCode returns an int "bin number" for an object. Hash-based collections — HashMap, HashSet (Collections, From the Inside) — use it to decide which bin to look in, and only then call equals within that bin.

    • The contract:

      1. If a.equals(b) is true, then a.hashCode() == b.hashCode() must be true. (Equal objects must go in the same bin.)

      2. Unequal objects may share a hash code (a collision — allowed, just slower).

      3. hashCode must stay the same while the object's relevant fields don't change.

    • equals itself must be: reflexive (a.equals(a)), symmetric (a.equals(b) ⇔ b.equals(a)), transitive, consistent, and a.equals(null) must be false.

    So: whenever you override equals, you must override hashCode too.

    Under the Hood — breaking it, then fixing it#

    A grid position class, overriding only equals:

    Java
    class PointBroken {
        final int x, y;
    
        PointBroken(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true; // same object → equal (fast path)
            if (!(o instanceof PointBroken p)) return false; // null or a different type → not equal
            return x == p.x && y == p.y; // compare the fields that define equality
        }
        // no hashCode! → inherits Object's, which is based on identity
    }

    And a correct one:

    Java
    class PointGood {
        ...same equals...
        @Override public int hashCode() { return Objects.hash(x, y); }    // built from the SAME fields as equals
    }
    Java
    Set<PointBroken> s1 = new HashSet<>();
    
    s1.add(new PointBroken(1, 2));
    
    Set<PointGood> s2 = new HashSet<>();
    
    s2.add(new PointGood(1, 2));
    
    System.out.println(
        new PointBroken(1, 2).equals(new PointBroken(1, 2)) +
            " " +
            s1.contains(new PointBroken(1, 2)) +
            " " +
            s2.contains(new PointGood(1, 2))
    );
    // true false true

    equals says the two broken points are equal — yet the set says it doesn't contain one. The two objects got different identity-based hash codes, so contains looked in the wrong bin and never even called equals. This exact bug happens in DSA whenever you put your own class (a grid cell, a state) into a HashSet or use it as a HashMap key — the classic example is "visited" sets in BFS (Graphs I (coming soon)).

    Rules of thumb:

    • Build equals and hashCode from exactly the same fields.

    • Use Objects.hash(...) and Objects.equals(a, b) (null-safe) — or let a record (Ch 12) or your IDE generate them.

    • Prefer immutable keys (Classes, Objects and Memory Ch 5). If you change a field of an object after putting it in a HashSet, its hash changes and the set can no longer find it.

    Check yourself

    4 questions
    1

    State the equals/hashCode contract.

    Show answer

    Equal objects (per equals) must have equal hash codes; equal hash codes don't require equal objects; the hash must be stable while the fields don't change.

    2

    Why did s1.contains(...) return false even though equals returned true?

    Show answer

    Without an overridden hashCode, the two equal points had different identity hash codes, so the set looked in a different bucket and never compared them with equals.

    3

    Why must hash-map keys not change while in the map?

    Show answer

    Their hash code would change, so the map would look in the wrong bucket and "lose" them.

    4

    What's a hash collision, and is it a bug?

    Show answer

    Two unequal objects with the same hash code; it's allowed and handled, just slower when frequent.