- It’s used by hash-based collections (like
HashMap,HashSet) to quickly find the object. - Think of it as a “bucket number” where the object might live.
🔗 What is equals()?
equals()checks logical equality between two objects.- In many cases, you override
equals()to compare meaningful fields (likeidinUser).
⚠️ Why do both exist?
Because hash-based collections (like HashMap and HashSet) use a two-step process to check if objects are equal:
1️⃣ Step 1 — hashCode check:
- Find the right “bucket” using
hashCode(). - Objects with different hash codes definitely cannot be equal — quick elimination.
2️⃣ Step 2 — equals check (if hash codes match):
- If two objects have the same hashCode, they might be equal, so Java calls
equals()to double-check.
🔥 The Golden Rule (Contract)
If two objects are equal (according to
equals()), they must have the samehashCode().
This ensures:
- Consistent behavior in hash-based collections.
- No two “equal” objects accidentally land in different hash buckets.
📚 Example — User Class
class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return id == user.id && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
✅ How Collections Use This
If you put a User into a HashSet, the process looks like this:
| Action | What happens? |
|---|---|
Adding User(1, "Bob") | hashCode() calculates bucket, user stored there |
Adding User(1, "Bob") again | Same hashCode() → bucket found → equals() checks if it’s a duplicate |
Adding User(2, "Alice") | Different hashCode() → different bucket |
🚨 Common Mistake
If you override equals() but forget to override hashCode(), two equal objects might end up in different buckets — breaking HashMap or HashSet.
Example (wrong):
class User {
private int id;
private String name;
@Override
public boolean equals(Object o) {
// Custom equality logic
}
// No hashCode override - breaks hash-based collections!
}
⚡ Summary Table
| Method | Purpose | Must Override Together? |
|---|---|---|
equals() | Check logical equality | ✅ Yes, always override both |
hashCode() | Calculate bucket number | ✅ Yes, always override both |
🔥 Golden Rule (Remember this!)
✅ If equals() says two objects are equal, their hashCode() must also be equal.
❌ If two objects have the same hashCode(), they are not guaranteed to be equal (collision is possible).
🎯 Quick Interview Pro Tip
✅ Always say:
- hashCode() is a performance optimization for hash-based collections.
- equals() is the real logical equality check.
- They must be consistent: if equals() returns true, hashCode() must be the same.