Answer
hashCode must be overridden with equals to preserve the Object contract for equal objects. • Hash-based collections choose buckets using hash codes before testing equality. • Equal objects with different hash codes may behave as separate keys. • A correct hash code uses the same equality-significant fields.
Example
Code
record Key(int id) {}
var set = new java.util.HashSet<Key>();
set.add(new Key(1));
System.out.println(set.contains(new Key(1)));Output
true
Quick Revision
Override hashCode whenever logical equals is overridden.