Repaso
Español
Java CoreIntermediateJV-14

If you override equals() in a class, what else must you override, and why?

Options

  1. toString(), so that the object prints in a readable way
  2. hashCode(), since equal objects must have the same hash code (Correct option)
  3. clone(), so that equal objects can also be copied
  4. Nothing else, because equals() works on its own

Answer

hashCode(), because equal objects must return the same hash code or HashMap/HashSet will misbehave

Why

The contract is: if a.equals(b) is true, then a.hashCode() == b.hashCode() must be true.

HashMap and HashSet first use the hash code to choose a bucket (a storage slot), and only then call equals inside that bucket. If two equal objects have different hash codes, they land in different buckets and the map will not find one when you search with the other.

Compute hashCode from the same fields you use in equals (Objects.hash(a, b)), or use a record.

Remember

Override equals => override hashCode with the same fields.

Key terms

Practice this question in Repaso