Skip to lesson

The equals and hashCode Contract

The equals and hashCode contract is one of the most repeated Java interview topics, because breaking it fails silently in a HashSet. The interviewer is checking whether you can predict that failure and write both methods correctly.

Recap: the contract rules

The hashCode contract says equal objects must return equal hash codes, and a hash code must not change while the fields used by equals stay the same. Unequal objects may share a hash code.

Object.equals compares references and Object.hashCode returns an identity-based number. The code shows that default behaviour before anything is overridden.

Example 1 · Default equals and hashCode compare identity

DefaultEquality.javaJava
class Ticket {    final String pnr;
    Ticket(String pnr) {        this.pnr = pnr;    }}
public class DefaultEquality {    public static void main(String[] args) {        Ticket a = new Ticket("4521367890");        Ticket b = new Ticket("4521367890");        Ticket c = a;
        System.out.println("a.equals(b): " + a.equals(b));        System.out.println("a.equals(c): " + a.equals(c));        System.out.println("same hash a, c: " + (a.hashCode() == c.hashCode()));        System.out.println("String equals: " + "4521367890".equals(new String("4521367890")));    }}
Output
a.equals(b): false
a.equals(c): true
same hash a, c: true
String equals: true

What this code does

  • Without overriding, equals is ==: two tickets with the same PNR are not equal, but a and c (one object) are.
  • String overrides equals and hashCode to compare text, which is why string keys work in maps.

When two objects should be equal by content, you override both methods and follow the contract.

Must know:

  • equals: reflexive, symmetric, transitive, consistent, and x.equals(null) is false
  • a.equals(b) → same hashCode; same hashCode does not mean equal (collisions are allowed)
  • HashSet and HashMap use hashCode first, then equals

Predict the output: equals without hashCode

A class overrides equals but not hashCode, and two equal objects are added to a HashSet. The set keeps both, and contains with a third equal object is false.

Step 3. Student overrides equals() but not hashCode(). s1 keeps an identity hash and lands in one bucket, here bucket 1. The equal object s2 has another hash, so contains(s2) searches another bucket, here bucket 2, finds it empty: not found.

Example 2 · equals overridden, hashCode forgotten

MissingHashCode.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
class Student {    final int roll;    final String name;
    Student(int roll, String name) {        this.roll = roll;        this.name = name;    }
    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        return roll == ((Student) o).roll;    }    // hashCode NOT overridden}
public class MissingHashCode {    public static void main(String[] args) {        Set<Student> set = new HashSet<>();        set.add(new Student(21, "Asha"));        set.add(new Student(21, "Asha"));        System.out.println("HashSet size: " + set.size());        System.out.println("HashSet contains: " + set.contains(new Student(21, "Asha")));
        List<Student> list = new ArrayList<>();        list.add(new Student(21, "Asha"));        System.out.println("ArrayList contains: " + list.contains(new Student(21, "Asha")));    }}
Output
HashSet size: 2
HashSet contains: false
ArrayList contains: true

What this code does

  • Each Student gets its own identity hash code, so the two equal students land in different buckets: size 2 and contains false. equals is never even called.
  • ArrayList.contains uses only equals, so it says true. The same class works in one collection and fails in another, a classic interview puzzle.

The reason is the lookup order. The set computes hashCode to choose a bucket before it ever calls equals. Identity hash codes differ, so equal objects go to different buckets and equals is never asked.

An ArrayList, which uses only equals, behaves correctly with the same class, which makes the bug confusing in real code.

Predict the output

Is it found?

Predict the exact output, then read the reason.

Round 1 of 3

hashCode is overridden but equals is not.

import java.util.HashSet;
import java.util.Set;
class Key {
final int id;
Key(int id) {
this.id = id;
}
@Override
public int hashCode() {
return id;
}
}
public class Round1 {
public static void main(String[] args) {
Set<Key> set = new HashSet<>();
set.add(new Key(1));
set.add(new Key(1));
System.out.println(set.size());
}
}

Writing correct equals and hashCode

Objects.hash(a, b, ...) builds one hash code from the given values with the 31 formula and treats null as 0. Pass exactly the fields that equals compares.

A correct equals(Object o) follows a fixed set of steps, and hashCode uses the same fields. The code writes a seat class the standard way.

Example 3 · A correct equals and hashCode

CorrectEquality.javaJava
import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Objects;import java.util.Set;
final class Seat {    private final String train;    private final String coach;    private final int number;
    Seat(String train, String coach, int number) {        this.train = train;        this.coach = coach;        this.number = number;    }
    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        Seat other = (Seat) o;        return number == other.number                && Objects.equals(train, other.train)                && Objects.equals(coach, other.coach);    }
    @Override    public int hashCode() {        return Objects.hash(train, coach, number);    }
    @Override    public String toString() {        return train + "/" + coach + "/" + number;    }}
public class CorrectEquality {    public static void main(String[] args) {        Set<Seat> booked = new HashSet<>();        booked.add(new Seat("12627", "S4", 33));        booked.add(new Seat("12627", "S4", 33));        booked.add(new Seat("12627", "S4", 34));        System.out.println("Booked seats: " + booked.size());        System.out.println("Is S4/33 taken? " + booked.contains(new Seat("12627", "S4", 33)));
        Map<Seat, String> passenger = new HashMap<>();        passenger.put(new Seat("12627", "B1", 7), "Ravi");        System.out.println("B1/7: " + passenger.get(new Seat("12627", "B1", 7)));        System.out.println("null-safe: " + new Seat(null, "S1", 1).equals(new Seat(null, "S1", 1)));    }}
Output
Booked seats: 2
Is S4/33 taken? true
B1/7: Ravi
null-safe: true

What this code does

  • equals compares all three fields, using Objects.equals so a null train does not throw; hashCode uses exactly the same three fields through Objects.hash.
  • Now duplicates are rejected, contains works with a fresh but equal object, and Seat can be a HashMap key. Making the class final with final fields also protects the hash code.

Steps: check this == o, reject null and other classes, cast, then compare the significant fields: == for primitives, Objects.equals for objects (null-safe). hashCode combines the same fields.

Use getClass() != o.getClass() when subclasses might add fields, to keep equality symmetric; instanceof is fine for final classes. Add @Override to both methods, and remember that records generate both for you.

Order of execution

Write equals in order

Put the steps of a correct equals and hashCode in the order you would say them.

Mutable fields in hashCode: the lost-key bug

The lost-key bug happens when a field used by hashCode changes after the object is stored in a HashSet or used as a HashMap key. The object stays in its old bucket, so every lookup misses it.

The code stores an object in a HashSet, changes a field that hashCode uses, and searches again.

Example 4 · The lost-key bug

LostKey.javaJava
import java.util.HashSet;import java.util.Objects;import java.util.Set;
class Locker {    String owner;                                // mutable and used in hashCode
    Locker(String owner) {        this.owner = owner;    }
    @Override    public boolean equals(Object o) {        return o instanceof Locker && Objects.equals(owner, ((Locker) o).owner);    }
    @Override    public int hashCode() {        return Objects.hashCode(owner);    }}
public class LostKey {    public static void main(String[] args) {        Set<Locker> lockers = new HashSet<>();        Locker l = new Locker("Asha");        lockers.add(l);
        l.owner = "Meera";                       // changes the hash code        System.out.println("size: " + lockers.size());        System.out.println("contains same object: " + lockers.contains(l));        System.out.println("removed: " + lockers.remove(l));        System.out.println("size after remove: " + lockers.size());
        l.owner = "Asha";                        // back to the old hash code        System.out.println("found again: " + lockers.contains(l));    }}
Output
size: 1
contains same object: false
removed: false
size after remove: 1
found again: true

What this code does

  • After owner changes, the object sits in Asha's bucket but its hash code now points to Meera's bucket, so even the very same object is not found and cannot be removed.
  • Changing the field back makes it findable again, which proves the object was never gone, only misplaced. Use immutable keys to avoid this.

contains, get and remove all look in the new bucket and fail, yet the set's size still counts the object.

The fix is design, not code: use immutable keys (String, records, immutable classes), or base equality on a field that never changes, such as an id. If you must change such a field, remove the object first and add it back after.

Find the bug

Find the equality bug

Tap the line that causes the bug.

A locker is stored in a HashSet, then its owner changes. Which line loses it?

Round 1 of 3

Common questions: collisions and why override both

A collision is when two unequal objects have the same hash code. It is legal: the collection then uses equals inside the bucket to tell them apart, and only speed suffers.

The code shows two different strings with the same hash code, and a constant hashCode that is legal but slow.

Example 5 · Collisions are legal; a constant hashCode is legal but slow

Collisions.javaJava
import java.util.HashMap;import java.util.Map;
class BadKey {    final int id;
    BadKey(int id) {        this.id = id;    }
    @Override    public boolean equals(Object o) {        return o instanceof BadKey && id == ((BadKey) o).id;    }
    @Override    public int hashCode() {        return 42;                               // legal, but every key collides    }}
public class Collisions {    public static void main(String[] args) {        System.out.println("\"Aa\" hash: " + "Aa".hashCode() + ", \"BB\" hash: " + "BB".hashCode());        Map<String, Integer> codes = new HashMap<>();        codes.put("Aa", 1);        codes.put("BB", 2);        System.out.println("Both stored: " + codes.size() + ", Aa=" + codes.get("Aa") + ", BB=" + codes.get("BB"));
        Map<BadKey, String> slow = new HashMap<>();        for (int i = 0; i < 1000; i++) {            slow.put(new BadKey(i), "v" + i);        }        System.out.println("Correct but slow: " + slow.size() + " keys, get(999) = " + slow.get(new BadKey(999)));    }}
Output
"Aa" hash: 2112, "BB" hash: 2112
Both stored: 2, Aa=1, BB=2
Correct but slow: 1000 keys, get(999) = v999

What this code does

  • "Aa" and "BB" collide, yet the map keeps both, because inside a bucket it uses equals to tell keys apart.
  • BadKey follows the contract, so results are correct, but all 1000 keys share one bucket, turning fast lookups into a long search.

"Aa" and "BB" both hash to 2112, and a HashMap still stores both, because it uses equals inside the bucket.

The opposite is illegal: equal objects with different hash codes break every hash collection. That is the whole answer to "why override both?": equals defines what "same" means, and hashCode must agree so that hash collections look in the right bucket.

Next step

Check your understanding

12 quick questions