Why must you override both equals() and hashCode() in Java?

The contract: equal objects must have the same hash code. If you override equals() but not hashCode(), two equal objects get different hash codes, and a HashSet keeps both:

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Main {
    static class Bad {
        final String name;
        Bad(String name) { this.name = name; }
        @Override public boolean equals(Object o) { return o instanceof Bad b && b.name.equals(name); }
    }

    static class Good {
        final String name;
        Good(String name) { this.name = name; }
        @Override public boolean equals(Object o) { return o instanceof Good g && g.name.equals(name); }
        @Override public int hashCode() { return Objects.hash(name); }
    }

    public static void main(String[] args) {
        Set<Bad> bad = new HashSet<>();
        bad.add(new Bad("Riya"));
        bad.add(new Bad("Riya"));
        System.out.println("Without hashCode: " + bad.size());     // wrong: 2

        Set<Good> good = new HashSet<>();
        good.add(new Good("Riya"));
        good.add(new Good("Riya"));
        System.out.println("With hashCode: " + good.size());       // right: 1
    }
}
Output

Without hashCode: 2
With hashCode: 1

The easy way: use a record, which writes both methods for you (Java Records).


Learn more about the similar topics:
Tutorials
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?