Blog

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

© 2025 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();
  }
}

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