Skip to main content
InterviewHubPRO
Section Overview
Q6

Question 6 of 50

Part 1: Core Language, Memory Model & Collections (1 - 10)

12%
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:

  1. If two objects are equal according to equals(Object), their hashCode() must return the identical integer value.
  2. If two objects have the same hash code, they are NOT necessarily equal (hash collision).
  3. If you override equals(), you MUST override hashCode(). 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);
    }
}