Junior — Middle
What is the relationship between hashCode and equals methods in Java?
sobes.tech AI
Answer from AI
In Java, the equals and hashCode methods are linked by a contract that guarantees the correct functioning of objects in hash-based collections (such as HashMap, HashSet).
Main rules:
- If two objects are equal according to the
equalsmethod (i.e.,a.equals(b)returnstrue), then they must have the samehashCode. - If the
hashCodeof two objects is different, then they are definitely not equal.
This is necessary so that when searching for an object in a hash structure, the correct bucket is first located by hashCode, and then objects are compared using equals.
Example:
class Person {
private String 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.equals(person.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}