Course contentsShow
← Java
Lesson 557 of 2,87013. The Object Class and Common MethodsFree lesson

Demonstrating the Bug: A Step-by-Step Example

Walk through a concrete example showing HashMap malfunction with equals-only override.

Demonstrating the Bug: A Step-by-Step Example

What you'll learn: You'll see exactly how overriding equals without hashCode causes HashMap to malfunction with a concrete, reproducible example.

The Setup

Let's walk through a real scenario that breaks HashMap. Imagine you create a Person class and override only equals (ignoring hashCode):

class Person {
    String name;
    
    Person(String name) {
        this.name = name;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Person)) return false;
        Person p = (Person) obj;
        return this.name.equals(p.name);
    }
    
    // hashCode NOT overridden - uses Object's default!
}

The Bug in Action

HashMap<Person, String> map = new HashMap<>();

Person alice1 = new Person("Alice");
map.put(alice1, "Engineer");

Person alice2 = new Person("Alice");

// This returns null, even though equals says alice1.equals(alice2) is true!
String job = map.get(alice2);
System.out.println(job); // null

Why It Breaks

  1. Inserting alice1: HashMap calls alice1.hashCode() (inherited from Object) and gets some value, say 12345. The entry goes into bucket 12345.

  2. Looking up with alice2: HashMap calls alice2.hashCode() (also from Object) and gets a different value, say 67890, because alice2 is a different object in memory.

  3. Wrong bucket searched: HashMap looks in bucket 67890, finds nothing, returns null—even though alice1.equals(alice2) is true!

The contract violation means logically equal objects land in different buckets, making lookup fail.

Key Takeaway: Always override hashCode when overriding equals—otherwise hash-based collections will fail to find logically equal keys, even when they exist in the map.