The equals and hashCode Contract
50 min · Intermediate
equals decides whether two objects mean the same thing; hashCode gives a number that hash collections use to find objects fast. They work as a pair: break the link between them, and HashSet and HashMap silently misbehave.
Topics in this lesson
- Recap: the contract rules
- Predict the output: equals without hashCode
- Writing correct equals and hashCode
- Mutable fields in hashCode: the lost-key bug
- Common questions: collisions and why override both
Interview questions this lesson answers
- What does
equalsdo by default? - What does
hashCodedo? - What is the equals and hashCode contract?
- What are the rules for a correct
equals? - Why must you override hashCode whenever you override equals?
- What happens if you override equals but not hashCode?
- What happens if you override hashCode but not equals?
- Can two unequal objects have the same hash code?
- Can two equal objects have different hash codes?
- Is returning a constant from hashCode legal?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.