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:
hashCode()directs it to the correct bucketequals()correctly identifies duplicates within that bucket- Looking up with a new but logically equal
Employeeworks—same hash code, same bucket,equalsreturns 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.