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

Fixing the Bug: Implementing Both Methods Correctly

Apply the correct pattern of overriding both equals and hashCode together to restore HashMap behavior.

Fixing the Bug: Implementing Both Methods Correctly

What you'll learn: How to restore HashMap and HashSet functionality by properly overriding both equals and hashCode together.

The Problem Recap

You've seen how overriding only equals without hashCode breaks hash-based collections. Objects that should be considered equal end up in different buckets, causing lookup failures and duplicate entries. The solution is straightforward: always override both methods together.

The Correct Implementation Pattern

When you override equals, immediately override hashCode to maintain the contract: equal objects must produce equal hash codes.

public class Employee {
    private int id;
    private String name;

    // Constructor, getters...

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Employee other = (Employee) obj;
        return id == other.id && Objects.equals(name, other.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

Why This Fixes HashMap

Now when you insert an Employee, both methods work in harmony:

  1. hashCode() directs it to the correct bucket
  2. equals() correctly identifies duplicates within that bucket
  3. Looking up with a new but logically equal Employee works—same hash code, same bucket, equals returns true
Map<Employee, String> map = new HashMap<>();
map.put(new Employee(1, "Alice"), "Engineer");
String title = map.get(new Employee(1, "Alice")); // ✓ Found! Returns "Engineer"

Key Takeaway: Always override equals and hashCode together—this single practice prevents an entire category of subtle, hard-to-debug collection bugs and ensures your objects work correctly with hash-based data structures.