Junior — Middle
Selgitage, kuidas on seotud Java meetodid equals ja hashCode ning miks nende õige rakendamine on oluline kogumite töös.
sobes.tech AI
Vastus AI-lt
In Java, the methods equals and hashCode are closely related and are used for comparing objects and storing them in collections such as HashMap, HashSet.
Rules:
- If two objects are equal according to the
equalsmethod (i.e.,a.equals(b) == true), they must have the samehashCode. - If the
hashCodeof objects differs,equalsshould returnfalsefor them.
Why is this important:
Hash-based collections first use hashCode for quick lookup of the bucket, then equals for exact comparison of objects within the bucket. If these methods are not correctly implemented, objects may not be found in the collection, even if they are logically equal.
Example of correct 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 field1.equals(myClass.field1) && field2 == myClass.field2;
}
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
Proper implementation of equals and hashCode ensures correct functioning of collections and prevents errors during search, addition, and removal of elements.