Video in progress
Why doesn't this `equals` work with `HashSet`?
class Money {
final long amount; final String currency;
Money(long amount, String currency) { this.amount = amount; this.currency = currency; }
public boolean equals(Money other) {
return amount == other.amount && currency.equals(other.currency);
}
@Override public int hashCode() { return Objects.hash(amount, currency); }
}
Set<Money> set = new HashSet<>(List.of(new Money(100, "UZS")));
System.out.println(set.contains(new Money(100, "UZS"))); // false
This method doesn't override equals, it overloads it: the parameter type is Money, not Object. HashSet calls equals(Object), which uses the identity comparison inherited from Object. As a result, equal objects are treated as not equal.
📖 Answer
hashCode is correct: both objects land in the same bucket. But inside the bucket, HashMap compares keys with key.equals(k), and the static type in that call is Object. Overload resolution happens at compile time, so equals(Object) is chosen, which is Object.equals, that is ==. The result is false.
The interesting part is that a direct call works:
new Money(100, "UZS").equals(new Money(100, "UZS")); // true: equals(Money) was chosen
Object o = new Money(100, "UZS");
new Money(100, "UZS").equals(o); // false
That is why a unit test (calling equals directly) passes, while the collection looks "broken". Most people slip up on exactly this in an interview.
The fix:
@Override
public boolean equals(Object o) {
return o instanceof Money m && amount == m.amount && currency.equals(m.currency);
}
If @Override had been there, the first version wouldn't have compiled at all, and the mistake would have been obvious right away. Best of all is record Money(long amount, String currency), where the compiler writes equals/hashCode correctly.
In code review, a quick and useful check is to search for equals( and find the ones whose parameter isn't Object; IntelliJ and SpotBugs warn about this too.
Sign up to mark studied questions and save your progress.