Card 03/ 08

ConceptDifficulty: Intermediate1 min

The equals and hashCode Contract

You override equals, change nothing else, and a value you put into a map cannot be got back out.

The rule binding equals and hashCode is that two objects which are equal must return the same hash code, the int that hashCode() returns and that a HashMap uses to decide where to store an object. The reverse is not required: unequal objects may share a hash code. Nothing in the language enforces the rule, so a class that overrides one method must override the other.

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 documentation of Object states the rule:

If two objects are equal according to equals, they must return the same hash code, the `int` that `hashCode()` returns and that a `HashMap` uses to decide where to store an object.

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, since there are far more possible objects than there are int values, and a hash-based collection, such as HashMap or HashSet, 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.