Card 08/ 08
Recap: equals, hashCode and toString
The defaults, the contract, how a map looks up a key, and the two ways keys get lost, with where each was.
The three inherited methods come down to the five ideas below, each listed with the card that covers it.
| The idea | Where |
|---|---|
Every class inherits equals, hashCode and toString with defaults | equals, hashCode and toString: The Methods Every Object Inherits |
The default equals compares addresses, not contents | equals Example: Two Identical Orders That Are Not Equal |
| Equal objects must have equal hash codes; equal hash codes need not mean equal objects | The equals and hashCode Contract |
hashCode chooses the bucket; equals decides what was found in it | How a HashMap Uses hashCode and equals: A Walkthrough |
| Override the two together, from fields that never change | Mutable HashMap Keys: Changing a Key Loses the Entry |
Breaking the contract throws nothing. It makes a value you stored impossible to find again and leaves size() insisting it is there, which is why this is worth getting right before anything depends on it.
← → move through sections and cards