Video in progress
What happens if equals() is overridden but hashCode() isn't?
Hash-based collections like HashMap and HashSet break: equal objects land in different buckets, so contains and get don't find them, and duplicates show up in a Set.
📖 Answer
The contract: if a.equals(b), then a.hashCode() == b.hashCode() must hold. The reverse isn't required: different objects can have the same hash (a collision).
class Phone {
final String number;
Phone(String n) { number = n; }
@Override public boolean equals(Object o) {
return o instanceof Phone p && p.number.equals(number);
}
// no hashCode: it's Object's, so it depends on the object's "address"
}
Set<Phone> set = new HashSet<>();
set.add(new Phone("+998901112233"));
set.contains(new Phone("+998901112233")); // almost always false
HashSet first finds the bucket by hash, then searches inside it with equals. The hashes differ, so it looks in another bucket and never sees the object.
The right way to write it:
@Override public int hashCode() { return number.hashCode(); }
// or Objects.hash(field1, field2)
The simplest way is to use a record: it generates both correctly. One more thing: the fields that go into the hash must not change while the object is sitting in a HashMap.
Sign up to mark studied questions and save your progress.