equals, hashCode, and toString Contracts

equals() defines logical equality when overridden. hashCode() must be consistent with equals: equal objects must have equal hash codes. toString() provides a readable representation for logs and debugging.

public record UserKey(String tenantId, String userId) {}

For mutable classes used as HashMap keys, changing fields involved in equality after insertion can make the entry effectively unreachable.

The equality relation should be reflexive, symmetric, transitive, consistent, and false for comparison with null.

Key Takeaways
  • equals defines logical equality.
  • Equal objects must have equal hash codes.
  • Do not mutate equality-defining state of a key while it is stored in a hash-based collection.