If two objects are equal by equals, they must return the same hashCode; unequal objects may share a hash but ideally do not. Break it and hash based collections misbehave: an object put into a HashMap becomes unreachable because lookup goes to a different bucket. equals must also be reflexive, symmetric, transitive and consistent, and mutating a field used in the hash after insertion loses the entry just as effectively.
Why interviewers ask this
It is a fundamentals check that predicts real bugs, especially in codebases using entities as map keys or in sets. The interviewer wants the one way implication stated correctly, plus the practical failure: a set that contains an item it cannot find. Follow ups usually go to JPA entities, where equals on a generated id is a classic trap, and to records, which generate both for you.
How to structure your answer
- State the contract as an implication, not an equivalence.
- Describe the concrete failure in a HashMap or HashSet.
- Mention mutability of fields used in the hash.
- Say what you do in practice: records, or a stable business key.
Example answer
The rule is one directional: equal objects must have equal hash codes, but equal hash codes do not imply equality, which is why a map still calls equals inside the bucket. If I override equals and forget hashCode, two objects that are equal land in different buckets, so I can put something into a HashSet and then have contains return false for an identical object. The subtler version is mutation. If a field used in the hash changes after the object is in a set, the entry is now in the wrong bucket and is effectively lost, which shows up as a leak because it can never be removed either. In practice I use records for value types so both are generated and consistent. For JPA entities I am careful, because using a generated id means equals changes when the entity is persisted, so an entity in a HashSet before flush behaves differently after. I use a stable natural or business key when there is one, and otherwise avoid putting unsaved entities in hash based collections.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- How would you implement equals for a JPA entity with a generated id?
- What does a record generate for you, and when is that not what you want?
- Why does a bad hash function degrade a HashMap even though it is correct?
Related java developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions