Junior — Middle
What is the importance of overriding the hashCode method for objects used in collections?
sobes.tech AI
Answer from AI
Overriding the hashCode method is important for the correct functioning of objects in hash-based collections such as HashMap, HashSet, and Hashtable. These collections use the object's hash code for quick lookup and storage. If hashCode is not overridden along with equals, objects that are considered equal by equals may have different hash codes, leading to incorrect behavior of the collections: for example, duplicates may not be detected, or an object may not be found during search.
Rules for overriding:
- If two objects are equal according to
equals, theirhashCodemust be the same. - If
equalsreturnsfalse, hash codes can be the same, but it is better to minimize collisions.
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 id == person.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
Here, objects are considered equal if they have the same id, and the hash code is built based on this field.