Junior — Middle
What mutual relationship should exist between the equals() and hashCode() methods in Java for correct object operation in collections?
sobes.tech AI
Answer from AI
In Java, the equals() and hashCode() methods must be consistent for objects to work correctly in collections, especially in such as HashMap and HashSet.
Main rules:
- If two objects are equal according to the
equals()method, then theirhashCode()methods must return the same value. - If
hashCode()of two objects is different, they are considered different andequals()is not called. - If
hashCode()is the same, objects may be either equal or not equal according toequals(), soequals()is called to verify.
Violating these rules can lead to incorrect behavior of collections, such as inability to find an object in HashSet or HashMap.
Example:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return this.id == other.id;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}