Why must you override equals() and hashCode() together?
Reviewed by Gurusankar M.
On this page
Concept Made Simple
Coffee Chat Question
“Why must you override equals() and hashCode() together?”
Remember It Faster
Mind Map Answer
They are a contract. If two objects are equal, they must return the same hashCode — otherwise hash-based collections break.
- equals()
- Are these two objects logically the same?
- hashCode()
- Which bucket does this object live in?
Override only equals() and a HashSet may store duplicates. Override only hashCode() and lookups may fail to find a matching key.
Learn by Doing
Hands-on Keyboard
record User(int id, String name) {}
// records auto-generate equals() & hashCode()
Set<User> set = new HashSet<>();
set.add(new User(1, "John"));
System.out.println(set.contains(new User(1, "John")));true
Think Beyond the Expected
What If?
What if hashCode() always returns a constant like 1?
It is technically valid, but every entry lands in the same bucket — the HashMap degrades to a list and lookups become O(n).
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: OOP (Core Java) Interview question: "Why must you override equals() and hashCode() together?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
Affiliate links
Tools for Your Developer Workspace
Equipment for a comfortable, productive setup.
As an Amazon Associate I earn from qualifying purchases.
- MonitorView on Amazon : BenQ EW2790U 27-inch Monitor (opens in a new tab)
BenQ EW2790U 27-inch Monitor
- LaptopView on Amazon : Acer Aspire One Laptop (opens in a new tab)
Acer Aspire One Laptop
- Office ChairView on Amazon : Wakefit Gravita Ergonomic Office Chair (opens in a new tab)
Wakefit Gravita Ergonomic Office Chair