What is the importance of hashCode() and equals() methods in Java?
The `equals()` method defines logical equality between objects — whether two instances should be considered the same value. The `hashCode()` method returns an integer used by hash-based data structures to bucket objects efficiently. They are defined on `Object` and meant to be overridden together.
The contract between them, specified in the Java documentation, is: if two objects are equal according to `equals()`, they must return the same `hashCode()`. The reverse is not required — two objects with the same hash code need not be equal (hash collisions are allowed).
This contract is critical for `HashMap`, `HashSet`, and `Hashtable`. When you call `map.put(key, value)`, the map computes `key.hashCode()` to find the right bucket, then uses `equals()` to find the exact entry within that bucket. If you override `equals()` without overriding `hashCode()`, two logically equal objects may land in different buckets, making retrieval silently fail — the map will not find a key even though an equal one exists.
The reverse violation is less catastrophic but still a performance problem: if all objects return the same hash code (constant hash), every entry lands in the same bucket, turning O(1) lookups into O(n) linked list scans.
For correct implementations: `equals()` must be reflexive, symmetric, transitive, consistent, and return false for null. `hashCode()` should use the same fields that `equals()` uses. IDEs and `Objects.hash()` / `Objects.equals()` can generate compliant implementations. Java 16+ records auto-generate both based on their components.
A subtle production bug: using a mutable field in `hashCode()` is dangerous when that object is stored in a `HashSet`. Mutating the field after insertion changes the hash, putting the object in the wrong bucket — the set can no longer find or remove it.
Explains the contract (equal objects must have equal hash codes) and why violating it breaks HashMap/HashSet lookups.
Also covers the symmetric/transitive/reflexive equals contract, the performance implication of poor hash distribution, and the danger of mutable fields in hash keys.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment