Senior
Tell me about equals and hashCode: the contract, why hashCode is needed
sobes.tech AI
Answer from AI
The contract between equals() and hashCode() in Java is as follows:
- If two objects are equal according to
equals(), then they must have the samehashCode(). - If
equals()returnsfalse, thenhashCode()can be the same or different, but it is better if it is different to reduce collisions.
Why hashCode is needed:
hashCode is used in hash data structures (e.g., HashMap, HashSet) for quick object lookup. When adding an object to a hash table, its hashCode is computed first to determine the bucket, and then equals is used for exact comparison.
If hashCode is not overridden along with equals, objects considered equal may have different hash codes, which can break collection behavior and cause errors.
Example:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(id, person.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}