equals() vs hashCode() in Java
Understand equals() vs hashCode() in Java: the contract, how HashMap uses both, why to override them together, with correct code and interview answers.
Expected Interview Answer
equals() defines whether two objects are logically equal, while hashCode() returns an integer bucket used by hash-based collections; the contract requires that equal objects must return the same hashCode, so the two methods must always be overridden together.
Collections like HashMap and HashSet first use hashCode() to find the right bucket, then use equals() to compare candidates within that bucket. If you override equals() but not hashCode(), two logically equal objects can land in different buckets and the collection fails to find or de-duplicate them. The contract also says unequal objects may share a hashCode (a collision), but equal objects may never disagree on it.
- Enables correct lookups in HashMap, HashSet and Hashtable
- Prevents duplicate objects in hash-based sets
- Keeps the equals/hashCode contract consistent
- Makes value-based objects usable as map keys
- Avoids subtle bugs where get() returns null for a present key
AI Mentor Explanation
hashCode() is like a batter's squad number that groups players by section on the team bus, quickly narrowing where to look, while equals() is the full identity check of name and photo that confirms the exact player. Two players might share a section by coincidence, but the real person is verified individually, and if the squad number ignored a player's true identity you would search the wrong section and never find them.
Step-by-Step Explanation
Step 1
Bucket first
Hash collections call hashCode() to pick a bucket, drastically narrowing the search space.
Step 2
Compare within bucket
Inside the bucket, equals() compares candidates to find the exact matching object.
Step 3
Honor the contract
Equal objects must return the same hashCode; unequal objects may collide but need not differ.
Step 4
Override together
Whenever you override equals(), override hashCode() too, using the same fields in both.
Step 5
Use consistent fields
Base both methods on the same immutable, identifying fields to keep behavior stable in collections.
What Interviewer Expects
- Stating the equals/hashCode contract precisely
- Explaining how HashMap uses both methods during lookup
- Knowing that overriding one without the other breaks collections
- Understanding that collisions are allowed but inconsistency is not
- Basing both methods on the same fields
Common Mistakes
- Overriding equals() but forgetting hashCode()
- Using different fields in equals() and hashCode()
- Assuming equal objects can have different hash codes
- Thinking a hashCode collision means the objects are equal
- Using mutable fields that change while the object is a map key
Best Answer (HR Friendly)
“equals() checks whether two objects mean the same thing, and hashCode() gives a quick number that helps collections group objects into buckets. They must agree, so in Java you always override both together, or things like HashMap and HashSet stop working correctly.”
Code Example
import java.util.Objects;
public class Employee {
private final int id;
private final String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee other = (Employee) o;
return id == other.id && Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name); // same fields as equals()
}
}import java.util.HashSet;
import java.util.Set;
Set<Employee> set = new HashSet<>();
set.add(new Employee(1, "Asha"));
boolean present = set.contains(new Employee(1, "Asha"));
// true only because equals() and hashCode() are both overriddenFollow-up Questions
- What exactly is the equals/hashCode contract in Java?
- What happens in a HashMap if you override equals() but not hashCode()?
- Why should hashCode() avoid mutable fields for map keys?
- How does Java 8's HashMap turn a long collision chain into a tree?
- Why is using getClass() sometimes preferred over instanceof in equals()?
MCQ Practice
1. According to the contract, if two objects are equal then their hash codes must be?
Equal objects are required to return the same hashCode; violating this breaks hash-based collections.
2. What can happen if you override equals() but not hashCode()?
Equal objects may land in different buckets, so get() or contains() can miss a logically present key.
3. Two unequal objects returning the same hashCode is called a?
A collision is allowed by the contract; collections resolve it with equals() inside the bucket.
Flash Cards
What does hashCode() return? — An int used by hash collections to choose a bucket for the object.
The core contract rule? — Equal objects (per equals) must have equal hashCodes; unequal objects may collide.
Override one, override the other? — Yes. Always override equals() and hashCode() together, using the same fields.
Handy helper methods? — Objects.equals() and Objects.hash() make correct implementations concise and null-safe.