Implement hashCode and equals
viaLeetCode
Problem For a custom class (e.g. Person{name, age, email}), implement equals() and hashCode() honoring their contract.
Input / Output
- equals(Object o): logical equality over significant fields; hashCode(): int consistent with equals.
Constraints
- Contract: equal objects MUST have equal hash codes; hashCode must be consistent across calls; equals must be reflexive, symmetric, transitive, null-safe (equals(null) → false).
Example
- new Person("A", 30) and new Person("A", 30) → equals true, same hashCode → usable as HashMap keys; violating this makes map.get() miss entries.
Expected approach
- equals: reference check (this == o), null/getClass() (or instanceof — know the symmetry debate) check, cast, field-by-field comparison via Objects.equals. hashCode: Objects.hash(fields) or the 31-multiplier accumulation (h = 31*h + field hash) — same fields as equals, no more, no fewer. Discussion: why 31, mutable fields as hash inputs breaking HashMap membership, and records/Lombok generating both.
asked …