Card 03/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
The Contract Between equals and hashCode
You override equals so that two orders with the same reference are equal. Nothing else changes, and a value you put into a map becomes impossible to get back out.
The two methods are not independent. There is one rule binding them, and nothing in the language enforces it.
If two objects are equal according to equals, they must return the same hash code.
| If | Then | Required? |
|---|---|---|
Two objects are equals | Their hash codes are the same | Yes — this is the contract |
| Two hash codes are the same | The objects are equals | No — collisions are expected and fine |
Two objects are not equals | Their hash codes differ | No, but different codes make maps faster |
The second row is the one people invert. Hash codes are allowed to collide — there are far more possible objects than there are int values — and a hash-based collection handles collisions by falling back to equals.
So the two methods are written together or not at all. Override equals alone and you have promised something about equality that every hash-based collection in the standard library will quietly fail to honour.