If you override equals() in a class, what else must you override, and why?
Options
toString(), so that the object prints in a readable wayhashCode(), since equal objects must have the same hash code (Correct option)clone(), so that equal objects can also be copied- 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.