Junior — Middle
Why can two objects considered equal via the equals method have different hashCode values?
sobes.tech AI
Answer from AI
If two objects are considered equal through the equals method, then according to the Java contract, their hashCode must be the same. However, in practice, sometimes equals is overridden, but hashCode is not, or implemented incorrectly, causing equal objects to have different hashCodes.
This leads to problems when using such objects in hash-based collections (e.g., HashMap, HashSet), where objects with different hashCodes may be stored in different buckets, even if they are equal.
Proper implementation requires:
- If a.equals(b) == true, then a.hashCode() == b.hashCode().
- The reverse is not necessary: different objects can have the same hashCode (collisions).
Example of incorrect implementation:
@Override
public boolean equals(Object o) {
// compare fields
}
// hashCode is not overridden, Object.hashCode() is used
To avoid problems, hashCode should always be overridden together with equals.