Interview Horizon

How are equals and hashCode related?

intermediate

6 min

Short answer

Objects considered equal must return the same hash code. Unequal objects may still share a hash code.

Explanation

Hash-based collections use the hash code to narrow the search and equality to identify matching keys.

Example

A record supplies implementations based on its components.

java
record UserId(String value) {}

Interview answer example

I treat the two methods as a contract. If my class defines logical equality, its hash code must use compatible information.

How are equals and hashCode related, and what can go wrong when only one is overridden?