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

Duplicate Keys with Broken hashCode: The Problem

See how overriding equals without hashCode causes HashMap to store duplicate logical keys.

Duplicate Keys with Broken hashCode: The Problem

What you'll learn: You'll see exactly what goes wrong when you override equals but forget to override hashCode in keys used with HashMap.

The Problem Exposed

When you override equals to define logical equality but leave hashCode with its default implementation (which returns different values for different object instances), HashMap can store what appear to be duplicate keys.

Here's why: HashMap uses hashCode first to decide which bucket to place an entry in. If two logically equal objects return different hash codes, they'll land in different buckets. When you later try to retrieve a value using a logically equal key, HashMap looks in the wrong bucket and finds nothing—even though the key "exists" in the map.

A Concrete Example

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

HashMap<Person, String> map = new HashMap<>();
Person p1 = new Person("Alice", 30);
map.put(p1, "Engineer");

Person p2 = new Person("Alice", 30);  // Logically equal to p1
System.out.println(map.get(p2));       // null! Should be "Engineer"
System.out.println(map.size());        // 1

map.put(p2, "Manager");
System.out.println(map.size());        // 2! Duplicate logical keys

Because p1 and p2 have different hash codes, they're treated as completely different keys despite being logically equal.

Key Takeaway: Breaking the equals-hashCode contract allows HashMap to store duplicate logical keys in different buckets, making retrieval unpredictable and corrupting the map's semantics. Always override both methods together.