Senior
What are equals and hashCode? What is the relationship between them?
sobes.tech AI
Answer from AI
In Java, the methods equals() and hashCode() are used for object comparison and working with hash data structures (e.g., HashMap, HashSet).
-
equals(Object obj) — determines whether the current object is equal to another object. By default, it compares references (i.e., whether the objects are the same in memory), but it is often overridden for content comparison.
-
hashCode() — returns an integer value (hash code), which is used for quick object lookup in hash tables.
Relationship between equals and hashCode:
- If two objects are equal according to equals(), their hashCode() must be the same.
- If hashCode() of objects is different, then equals() will definitely return false.
This is important for the correct functioning of hash-based collections. Violating this contract leads to errors in object search and storage.
Example of overriding:
@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);
}