Common equals and hashCode Mistakes
You'll learn: The three most frequent errors developers make when implementing equals and hashCode, and why they break your code.
The Most Common Pitfalls
Even experienced developers stumble over these mistakes. Let's examine the three biggest traps:
1. Overriding equals Without hashCode
This is the cardinal sin. Remember the contract: equal objects must have the same hash code. If you override equals but not hashCode, your objects will behave correctly with == comparisons but fail mysteriously in HashMap or HashSet.
public class Person {
private String name;
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person)) return false;
Person p = (Person) obj;
return Objects.equals(name, p.name);
}
// BUG: No hashCode override!
// Two equal Persons will likely have different hash codes
}
2. Using Mutable Fields
If you base equals and hashCode on fields that can change, you create chaos. Imagine adding an object to a HashSet, then modifying it—the hash code changes, and the object becomes "lost" in the set.
// DANGEROUS:
return Objects.hash(balance); // balance can change!
Best practice: Use only immutable fields (like IDs) or accept that modifying objects in hash-based collections is forbidden.
3. Violating Symmetry with Inheritance
When subclasses override equals, you can break symmetry: a.equals(b) might return true, but b.equals(a) returns false. This happens when parent and child classes use different equality logic.
// If parent checks only name, but child adds age check:
// parent.equals(child) might differ from child.equals(parent)
Key Takeaway: Always override equals and hashCode together, use only immutable fields, and be extremely careful with inheritance—prefer composition or make equals final to prevent subclass inconsistencies.