Junior — Middle
Explain how the equals method affects the behavior of keys in HashMap?
sobes.tech AI
Answer from AI
In HashMap, keys are stored as hash codes, but the equals method is used to determine key uniqueness. When searching or inserting an element, the hash code of the key is first computed to find the appropriate bucket, and then equals is called to compare keys within that bucket. If the equals method is implemented incorrectly or not overridden, HashMap may consider different objects as the same or vice versa, leading to errors during search or duplication of keys.
Example:
class Person {
String name;
int id;
@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);
}
}
// If equals and hashCode are consistent, HashMap will correctly identify keys by id.