Card 03/ 08

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.

The Object contract, in one sentence
What the contract requires in each direction
IfThenRequired?
Two objects are equalsTheir hash codes are the sameYes — this is the contract
Two hash codes are the sameThe objects are equalsNo — collisions are expected and fine
Two objects are not equalsTheir hash codes differNo, 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.