Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
What is the contract between `equals()` and `hashCode()`?
junior LevelCode ExamplejavaCore Language
In Simple Words:
- If two objects are equal according to
equals(Object), theirhashCode()must return the identical integer value. - If two objects have the same hash code, they are NOT necessarily equal (hash collision).
- If you override
equals(), you MUST overridehashCode(). Failing to do so breaks hash-based collections (HashMap,HashSet), causing lookups to fail even when the key object exists.
java
public class UserKey {
private final String userId;
public UserKey(String userId) { this.userId = userId; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserKey other)) return false;
return Objects.equals(this.userId, other.userId);
}
@Override
public int hashCode() {
return Objects.hash(userId);
}
}