Skip to lesson

equals and hashCode in collections

Every collection has to answer one question again and again: "Is this the same item?" Lists ask equals(), hash collections ask hashCode() and then equals(), and sorted collections ask compareTo() or a Comparator. Most collection bugs come from these methods disagreeing with each other.

Who asks which method

A small class prints a message whenever equals, hashCode or compareTo runs. The program calls contains on a list, a HashSet and a TreeSet to show which method each one uses.

Example 1 · Watching which method each collection calls

WhoCallsWhatDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
class Roll implements Comparable<Roll> {    static boolean spy = false;    final int no;
    Roll(int no) {        this.no = no;    }
    @Override    public boolean equals(Object o) {        if (!(o instanceof Roll other)) {            return false;        }        if (spy) {            System.out.println("  equals(" + no + ", " + other.no + ")");        }        return no == other.no;    }
    @Override    public int hashCode() {        if (spy) {            System.out.println("  hashCode(" + no + ")");        }        return no;    }
    @Override    public int compareTo(Roll other) {        if (spy) {            System.out.println("  compareTo(" + no + ", " + other.no + ")");        }        return Integer.compare(no, other.no);    }}
public class WhoCallsWhatDemo {    public static void main(String[] args) {        List<Roll> list = new ArrayList<>(List.of(new Roll(1), new Roll(2), new Roll(3)));        Set<Roll> hashSet = new HashSet<>(list);        Set<Roll> treeSet = new TreeSet<>(list);        Roll.spy = true;
        System.out.println("ArrayList.contains(3):");        System.out.println("  -> " + list.contains(new Roll(3)));
        System.out.println("HashSet.contains(3):");        System.out.println("  -> " + hashSet.contains(new Roll(3)));
        System.out.println("TreeSet.contains(3):");        System.out.println("  -> " + treeSet.contains(new Roll(3)));    }}
Output
ArrayList.contains(3):
  equals(3, 1)
  equals(3, 2)
  equals(3, 3)
  -> true
HashSet.contains(3):
  hashCode(3)
  equals(3, 3)
  -> true
TreeSet.contains(3):
  compareTo(3, 2)
  compareTo(3, 3)
  -> true

What this code does

  • Each method prints a line when it runs. ArrayList called equals three times, once for every item, until it found 3.
  • HashSet called hashCode once to reach the right bucket, then equals once. TreeSet only called compareTo, walking down its sorted tree.

Knowing which method a collection calls tells you which method must be correct. When a contains, remove or get gives a strange answer, this list tells you where to look:

  • ArrayList, LinkedList, ArrayDeque, PriorityQueue: contains, indexOf and remove(Object) call equals() on each item, one by one.
  • HashSet, HashMap, LinkedHashSet, LinkedHashMap: hashCode() picks the bucket, then equals() checks only the items in that bucket.
  • TreeSet, TreeMap: only compareTo() or the Comparator. A result of 0 means "same item"; equals() is never called.
  • Collections.frequency and List.equals also use equals().

equals and hashCode must agree

A bucket is one slot of a hash table. hashCode() decides which bucket an item goes to, and equals() is then asked only about the items already in that same bucket.

One student class has equals only, and another has both equals and hashCode. The program adds equal students to a list and to a HashSet and checks contains.

Example 2 · Common mistake: equals without hashCode

MissingHashCodeDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Objects;import java.util.Set;
class HalfStudent {    final String roll;
    HalfStudent(String roll) {        this.roll = roll;    }
    @Override    public boolean equals(Object o) {        return o instanceof HalfStudent s && roll.equals(s.roll);    }}
class Student {    final String roll;
    Student(String roll) {        this.roll = roll;    }
    @Override    public boolean equals(Object o) {        return o instanceof Student s && roll.equals(s.roll);    }
    @Override    public int hashCode() {        return Objects.hash(roll);    }}
public class MissingHashCodeDemo {    public static void main(String[] args) {        List<HalfStudent> halfList = new ArrayList<>();        halfList.add(new HalfStudent("CS101"));        Set<HalfStudent> halfSet = new HashSet<>();        halfSet.add(new HalfStudent("CS101"));        halfSet.add(new HalfStudent("CS101"));
        System.out.println("equals only:");        System.out.println("  list.contains -> " + halfList.contains(new HalfStudent("CS101")));        System.out.println("  set size      -> " + halfSet.size());        System.out.println("  set.contains  -> " + halfSet.contains(new HalfStudent("CS101")));
        List<Student> list = new ArrayList<>();        list.add(new Student("CS101"));        Set<Student> set = new HashSet<>();        set.add(new Student("CS101"));        set.add(new Student("CS101"));
        System.out.println("equals + hashCode:");        System.out.println("  list.contains -> " + list.contains(new Student("CS101")));        System.out.println("  set size      -> " + set.size());        System.out.println("  set.contains  -> " + set.contains(new Student("CS101")));    }}
Output
equals only:
  list.contains -> true
  set size      -> 2
  set.contains  -> false
equals + hashCode:
  list.contains -> true
  set size      -> 1
  set.contains  -> true

What this code does

  • HalfStudent has equals but uses Object's hashCode, which differs for every object. So the ArrayList finds the student, but the HashSet lets in a duplicate and cannot find it. The hash codes are random, so this almost always happens, which makes the bug hard to spot.
  • Student builds its hash code from the same field as equals with Objects.hash(roll), so both collections agree.

The rule from the Object class is: equal objects must have equal hash codes. A hash collection relies on it. It first uses hashCode() to jump to one bucket, and only then asks equals() about the items in that bucket. If two equal students have different hash codes, they land in different buckets, and equals() is never even asked.

So a class with equals() but no hashCode() works in an ArrayList but fails in a HashSet: duplicates get in and contains says false. A class with neither method compares by identity (same object in memory), so even list.contains fails for a new but equal object. Always override both, using the same fields.

Order of execution

How HashSet.add decides

Put the steps of add(newItem) in the order Java does them.

The lost-key bug

A seat is stored as a HashMap key, and then its coach changes. The program tries to find the entry again in four ways.

Example 3 · The lost-key bug in a HashMap

LostKeyDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Objects;
class Seat {    String coach;    int berth;
    Seat(String coach, int berth) {        this.coach = coach;        this.berth = berth;    }
    @Override    public boolean equals(Object o) {        return o instanceof Seat s && coach.equals(s.coach) && berth == s.berth;    }
    @Override    public int hashCode() {        return Objects.hash(coach, berth);    }
    @Override    public String toString() {        return coach + "-" + berth;    }}
public class LostKeyDemo {    public static void main(String[] args) {        Map<Seat, String> bookings = new HashMap<>();        Seat seat = new Seat("S4", 12);        bookings.put(seat, "Kavya");        System.out.println("Before: " + bookings.get(seat));
        seat.coach = "S5";
        System.out.println("get(same object):  " + bookings.get(seat));        System.out.println("get(new S5-12):    " + bookings.get(new Seat("S5", 12)));        System.out.println("get(new S4-12):    " + bookings.get(new Seat("S4", 12)));        System.out.println("containsKey(seat): " + bookings.containsKey(seat));        System.out.println("Still inside:      " + bookings + ", size " + bookings.size());
        bookings.remove(seat);        System.out.println("After remove, size " + bookings.size());        bookings.put(seat, "Kavya again");        System.out.println("After put again, size " + bookings.size());    }}
Output
Before: Kavya
get(same object):  null
get(new S5-12):    null
get(new S4-12):    null
containsKey(seat): false
Still inside:      {S5-12=Kavya}, size 1
After remove, size 1
After put again, size 2

What this code does

  • After seat.coach = "S5", every lookup fails, by the same object, by new S5-12 and by the old S4-12, yet the entry is still printed and counted.
  • Even remove cannot reach it, and putting the same object again adds a second entry. The first entry stays stuck in the map.

A HashMap stores each key in the bucket for the hash code it had when it was added. If you later change a field that hashCode() uses, the key is now in the wrong bucket. get, containsKey and remove look in the new bucket and find nothing. A lookup with the old values reaches the old bucket, but equals() now fails.

The entry is still inside: the map's size counts it, and a loop over the map prints it. But no lookup can reach it, and put with the changed key adds a second entry. The same happens to an element of a HashSet. The fix: never change a field used by equals or hashCode while the object is a key. If you must, remove it, change it, then put it back.

Fields used in equals and hashCode should be final. Then the bug cannot happen.

Sorted collections trust compareTo

An order is consistent with equals when compare(a, b) == 0 exactly when a.equals(b). A TreeSet needs this to avoid dropping items that are different but compare as 0.

Three toppers go into a TreeSet, first ordered by marks only and then by marks and name. Count how many stay.

Example 4 · A TreeSet comparator that drops students

TreeSetDropDemo.javaJava
import java.util.Comparator;import java.util.Set;import java.util.TreeSet;
record Topper(String name, int marks) {}
public class TreeSetDropDemo {    public static void main(String[] args) {        Comparator<Topper> byMarks = Comparator.comparingInt(t -> t.marks());
        Set<Topper> wrong = new TreeSet<>(byMarks);        wrong.add(new Topper("Asha", 92));        wrong.add(new Topper("Bilal", 88));        wrong.add(new Topper("Chirag", 92));        System.out.println("Marks only: " + wrong.size() + " " + wrong);        System.out.println("Contains Zoya 88? " + wrong.contains(new Topper("Zoya", 88)));
        Comparator<Topper> full = byMarks.thenComparing(t -> t.name());        Set<Topper> right = new TreeSet<>(full);        right.add(new Topper("Asha", 92));        right.add(new Topper("Bilal", 88));        right.add(new Topper("Chirag", 92));        System.out.println("Marks, then name: " + right.size() + " " + right);        System.out.println("Contains Zoya 88? " + right.contains(new Topper("Zoya", 88)));    }}
Output
Marks only: 2 [Topper[name=Bilal, marks=88], Topper[name=Asha, marks=92]]
Contains Zoya 88? true
Marks, then name: 3 [Topper[name=Bilal, marks=88], Topper[name=Asha, marks=92], Topper[name=Chirag, marks=92]]
Contains Zoya 88? false

What this code does

  • With marks only, Chirag (92) compares as 0 with Asha (92), so the TreeSet treats him as a duplicate and drops him. It even claims to contain Zoya, who was never added.
  • Adding thenComparing(t -> t.name()) makes the order consistent with equals: all three stay, and the Zoya check is false.

TreeSet and TreeMap decide "same item" only by compareTo() or the Comparator. If your comparator compares only marks, two different students with the same marks count as duplicates, and the second one is silently dropped. Even contains answers true for any student with those marks.

An order is consistent with equals when compare(a, b) == 0 exactly when a.equals(b). For a TreeSet, add tie-breakers with thenComparing until only truly equal items compare as 0. For sorting a List, a tie is fine, because a list keeps every item.

Safe keys: immutable values

A record, an int[] and a List are tried as map keys. Then a payment checker uses a record in a HashSet to catch duplicates.

Example 5 · Records are safe keys; arrays are not

SafeKeysDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;
record SeatKey(String coach, int berth) {}
public class SafeKeysDemo {    public static void main(String[] args) {        Map<SeatKey, String> chart = new HashMap<>();        chart.put(new SeatKey("B2", 33), "Gaurav");        System.out.println("Record key: " + chart.get(new SeatKey("B2", 33)));        System.out.println("Two equal records: " + new SeatKey("B2", 33).equals(new SeatKey("B2", 33)));
        Map<int[], String> byArray = new HashMap<>();        byArray.put(new int[] {2, 33}, "Gaurav");        System.out.println("int[] key: " + byArray.get(new int[] {2, 33}));
        Map<List<Integer>, String> byList = new HashMap<>();        byList.put(List.of(2, 33), "Gaurav");        System.out.println("List key: " + byList.get(List.of(2, 33)));    }}
Output
Record key: Gaurav
Two equal records: true
int[] key: null
List key: Gaurav

What this code does

  • Two separate SeatKey records with the same values are equal and have the same hash code, so get finds the booking.
  • An int[] key uses identity, so a new array with the same numbers finds nothing. List.of(2, 33) compares by contents and works.

Example 6 · Full example: catching duplicate UPI payments

DuplicatePaymentDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeMap;
record Payment(String upiId, int amount, String time) {}
public class DuplicatePaymentDemo {    public static void main(String[] args) {        List<Payment> received = List.of(                new Payment("rahul@okaxis", 1200, "10:01"),                new Payment("meena@ybl", 450, "10:03"),                new Payment("rahul@okaxis", 1200, "10:01"),                new Payment("arun@paytm", 800, "10:05"),                new Payment("meena@ybl", 450, "10:09"));
        Set<Payment> seen = new HashSet<>();        List<Payment> duplicates = new ArrayList<>();        Map<String, Integer> totals = new TreeMap<>();
        for (Payment p : received) {            if (!seen.add(p)) {                duplicates.add(p);                continue;            }            totals.merge(p.upiId(), p.amount(), (a, b) -> a + b);        }
        System.out.println("Unique payments: " + seen.size());        System.out.println("Duplicates: " + duplicates);        System.out.println("Totals by UPI id: " + totals);    }}
Output
Unique payments: 4
Duplicates: [Payment[upiId=rahul@okaxis, amount=1200, time=10:01]]
Totals by UPI id: {arun@paytm=800, meena@ybl=900, rahul@okaxis=1200}

What this code does

  • Payment is a record, so two payments with the same id, amount and time are equal. seen.add(p) returns false for the repeated one, which marks it as a duplicate.
  • Meena's second payment has a different time, so it is a new payment and her total is 900. A TreeMap prints the totals in A to Z order of UPI id.

The safest keys never change. String, Integer and enums are immutable and already have correct equals and hashCode. A record is the easiest way to make your own key: its fields are final, and Java writes equals, hashCode and toString from all of them.

Two traps remain. Arrays do not override equals, so an int[] key is only found with the very same array object; use List.of(...) or a record instead. And a record is only as safe as its fields: a record holding an ArrayList changes when that list changes. Copy it in the record's compact constructor with List.copyOf.

Next step

Check your understanding

12 quick questions