Testing Your equals and hashCode Implementations
What you'll learn: How to verify that your custom equals and hashCode methods work correctly with HashSet and other Set implementations.
Why Testing Matters
You've learned that breaking the equals/hashCode contract causes HashSet to malfunction—duplicates sneak in, lookups fail, and chaos ensues. But how do you prove your implementation is correct before deploying it? Testing is your safety net.
The Basic Testing Strategy
Test with HashSet operations: The simplest approach is to actually use your objects in a HashSet and verify the expected behavior:
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30); // Equal to p1
Set<Person> set = new HashSet<>();
set.add(p1);
set.add(p2); // Should not create duplicate
// Test 1: Set should contain only one element
assert set.size() == 1 : "Duplicates detected!";
// Test 2: Both objects should be found
assert set.contains(p1) : "Original not found!";
assert set.contains(p2) : "Equal object not found!";
What to Test
- Reflexivity: An object equals itself:
p1.equals(p1)must be true - Symmetry: If
p1.equals(p2), thenp2.equals(p1) - Consistency hashCode: Equal objects have equal hash codes:
p1.hashCode() == p2.hashCode() - HashSet deduplication: Adding equal objects shouldn't increase size
- Lookup reliability:
contains()finds equal objects even if they're different instances
Testing TreeSet Too
If your class implements Comparable, test that compareTo is consistent with equals:
TreeSet<Person> treeSet = new TreeSet<>();
treeSet.add(p1);
treeSet.add(p2);
assert treeSet.size() == 1 : "TreeSet duplicates!";
Key Takeaway: Always test your equals and hashCode implementations by actually using the objects in a HashSet—verify no duplicates appear, lookups succeed, and behavior matches expectations.