Course contentsShow
← Java
Lesson 1087 of 2,87025. Set ImplementationsFree lesson

Breaking HashSet with Bad equals

Observe how a broken equals method prevents duplicate detection even with correct hashCode.

Breaking HashSet with Bad equals

What you'll learn: You'll see how a broken equals() method sabotages HashSet's duplicate detection, even when hashCode() is correctly implemented.

The Problem

You've learned that hashCode() and equals() must work together for HashSet to function properly. But what happens when equals() is broken while hashCode() is correct?

When two objects have identical hashCode() values, HashSet looks in the same bucket and then uses equals() to determine if they're truly duplicates. If equals() is implemented incorrectly—returning false when it should return true—HashSet will store what should be duplicates as separate objects.

The Broken equals Scenario

Imagine a Person class where hashCode() correctly uses the name field, but equals() always returns false or incorrectly compares fields:

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return name.hashCode(); // Correct!
    }

    @Override
    public boolean equals(Object obj) {
        return false; // Broken: always says "not equal"
    }
}

Now watch what happens:

HashSet<Person> set = new HashSet<>();
set.add(new Person("Alice"));
set.add(new Person("Alice"));
System.out.println(set.size()); // 2, not 1!

Both Person objects hash to the same bucket (same hashCode()), but when HashSet calls equals() to check for duplicates, it gets false. HashSet concludes they're different objects and stores both.

The Real-World Analogy

It's like a filing cabinet where folders are correctly labeled (good hashCode()), but the clerk inside each drawer is blind and can't actually read document contents to verify duplicates (broken equals()).

Key Takeaway: A broken equals() method breaks duplicate detection in HashSet, even when hashCode() is implemented correctly—both methods must be properly synchronized.