Junior — Middle
Каким образом реализованы методы equals и hashCode, и какие существуют правила их взаимодействия?
sobes.tech AI
Answer from AI
In Java, the equals and hashCode methods are related and must be implemented according to certain rules:
- If two objects are equal according to
equals(), they must have the samehashCode(). - If
equals()returnsfalse, thenhashCode()can be the same, but minimizing collisions is desirable.
Implementation rules:
- Override
equals()to compare logical equality of objects, not just references. - Override
hashCode()so that it aligns with the logic ofequals().
Example implementation:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
return Objects.equals(field1, myClass.field1) &&
Objects.equals(field2, myClass.field2);
}
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
Violating these rules can lead to incorrect behavior of collections, such as HashMap or HashSet.