Difficulty: Beginner
What is the difference between == and equals()? Why must you override hashCode() whenever you override equals()?
Let me tell you why this question keeps surviving in interviews for a decade: bugs from breaking this contract are silent. Your code compiles, your tests on small data pass, and then a HashMap lookup randomly returns null in production. Interviewers want to see that you understand why.
First the simple part. The operator == compares what is stored in the variable. For primitives, that is the actual value, so 5 == 5 is true. For objects, the variable stores a reference, so == asks whether two references point to the exact same object in memory. That is identity.
The equals method, defined in Object, is meant to check logical equality. But the default implementation in Object is just this == obj, so unless a class overrides it, equals behaves the same as ==. String, Integer, List, LocalDate and most library classes override equals to compare content. Your own classes do not, unless you write it.
Now the contract. When you override equals, it must be reflexive (x equals x), symmetric (if x equals y then y equals x), transitive, consistent (same result on repeated calls if nothing changed) and return false for null. Symmetry is where inheritance bugs creep in, for example when a subclass compares with instanceof against the parent in one direction only.
The hashCode contract says: if two objects are equal according to equals, they must return the same hashCode. The reverse is not required; two unequal objects may share a hash code, that is just a collision and costs performance. Also, hashCode must return the same value across calls during one execution as long as the fields used in equals are unchanged.
Why does this matter? Hash-based collections such as HashMap, HashSet and Hashtable use hashCode to pick a bucket, and then use equals to find the exact key within the bucket. Imagine two Employee objects with the same id that are equal by your equals. If you did not override hashCode, each object inherits the identity-based hash from Object, so they land in different buckets. The map then never even calls equals, and get returns null for a key that is logically present. A HashSet would happily store duplicates.
Think of it as a library. The hash code is the shelf number, and equals is checking the exact book on that shelf. If two identical copies are sent to different shelves, you will never realize they are duplicates.
Best practice: use the same fields in both methods, and write them with Objects.equals and Objects.hash, or let your IDE or a record generate them. Records automatically generate correct equals and hashCode from all components.
Another important trap: do not use mutable fields in hashCode for objects used as map keys. If a key changes after insertion, its hash changes and the entry becomes unreachable, a subtle memory leak.
Finally, remember that Strings are special because == may accidentally work due to the pool, but you should never rely on that. Always use equals for content, and use Objects.equals(a, b) when either side may be null to avoid NullPointerException.
import java.util.*;
public class ContractDemo {
static class BadKey {
final int id;
BadKey(int id) { this.id = id; }
@Override public boolean equals(Object o) {
return o instanceof BadKey b && b.id == id;
}
}
static class GoodKey {
final int id;
GoodKey(int id) { this.id = id; }
@Override public boolean equals(Object o) {
return o instanceof GoodKey g && g.id == id;
}
@Override public int hashCode() { return Objects.hash(id); }
}
public static void main(String[] args) {
Map<BadKey, String> bad = new HashMap<>();
bad.put(new BadKey(1), "A");
System.out.println(bad.get(new BadKey(1)));
Map<GoodKey, String> good = new HashMap<>();
good.put(new GoodKey(1), "A");
System.out.println(good.get(new GoodKey(1)));
}
}
BadKey inherits an identity-based hashCode, so two equal keys go to different buckets and get returns null (in practice always). GoodKey follows the contract and the lookup succeeds.
equals, hashCode, Object Identity, HashMap, Contract