Junior — Middle
Why is it important to override the hashCode method in your classes?
sobes.tech AI
Answer from AI
Overriding the hashCode method is important for objects to work correctly in hash-based collections (e.g., HashMap, HashSet).
Rules:
- If two objects are equal according to the
equals()method, then theirhashCode()must return the same value. - If
hashCodeis not overridden, objects with the same data may have different hashes, leading to incorrect collection behavior.
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);
}
Here, id is a unique identifier of the object.