Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javahard

Why must `equals()` and `hashCode()` follow a contract?

Tags
#equals#hashcode#hashmap
Back to categoryPractice quiz

Answer

If two objects are equal according to `equals()`, they must have the same `hashCode()`. Hash-based collections (HashMap/HashSet) rely on it; breaking the contract leads to “missing” entries and hard-to-debug behavior.

final class User {
  private final String email;

  User(String email) {
    this.email = email;
  }

  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof User)) return false;
    return email.equals(((User) o).email);
  }

  @Override public int hashCode() {
    return email.hashCode();
  }
}

Advanced answer

Deep dive

Hash-based collections work in two steps: 1) Use `hashCode()` to pick a bucket. 2) Use `equals()` to find the matching key inside that bucket.

Contract highlights:

  • If `a.equals(b)` is true, then `a.hashCode() == b.hashCode()` must be true.
  • The reverse is not required (hash collisions are allowed).
  • Both should be consistent over time for keys stored in maps/sets.

Practical guidance

  • Use immutable fields for equality keys (or never mutate them while the object is in a HashMap/HashSet).
  • Prefer records/value objects for stable equality.

Common pitfalls

  • Mutating fields used by `hashCode()` after inserting into a HashSet (entry becomes “lost”).
  • Overriding `equals()` but forgetting `hashCode()`.
  • Poor hash functions that cause many collisions (performance drops).

Related questions

Java
HashMap vs ConcurrentHashMap: when should you use each?
#java#collections#concurrency
Java
HashMap vs LinkedHashMap — what’s the practical difference?
#hashmap#linkedhashmap#collections
Java
HashMap vs ConcurrentHashMap — what’s the practical difference?
#hashmap#concurrency
#concurrenthashmap
Java
In Java, what’s the difference between `==` and `.equals()`?
#equals#reference#string
Data Structures
Ordered map (TreeMap) vs HashMap: when would you choose an ordered map?
#map#treemap#hashmap