The contract - equals must be reflexive, symmetric, transitive and consistent, and return false for null. - If a.equals(b) is true, then a.hashCode() must equal b.hashCode(). - Equal hash codes do not require equality (collisions are allowed, but hurt performance). Correct implementation (or simply use a record, which generates both): public final class Sku { private final String code; public Sku(String code) { this.code = code.toUpperCase(Locale.ROOT); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Sku other)) return false; return code.equals(other.code); } @Override public int hashCode() { return code.hashCode(); } } Production bugs caused by inconsistent implementations 1. Overriding equals but not hashCode Two equal objects land in different buckets: HashSet contains duplicates, HashMap.get returns null for a key that "exists", and caches miss constantly. 2. Mutable fields in equals and hashCode Changing a field after inserting an object into a HashSet or as a HashMap key leaves it in the wrong bucket: contains() returns false, remove() silently fails, and memory leaks because entries can never be removed. 3. JPA entities - Using a generated ID in equals/hashCode: before persist the ID is null, after persist it changes, so an entity added to a Set before saving "disappears" afterwards. - Including lazy-loaded associations triggers extra queries or LazyInitializationException, and Hibernate proxies may fail getClass() comparisons. - Common solutions: a natural business key, a UUID assigned at creation, or equality based on ID with a constant hashCode (as recommended by several Hibernate experts). 4. Inconsistent with compareTo TreeSet and TreeMap use compareTo, not equals. If they disagree (BigDecimal("1.0") vs BigDecimal("1.00") are not equal but compare as 0), sorted and hashed collections behave differently. 5. Inheritance and symmetry A subclass adding fields to equals can break symmetry (a.equals(b) but not b.equals(a)). Prefer final classes, records or composition. 6. Floating-point and arrays Use Double.compare for doubles and Arrays.equals and Arrays.hashCode for array fields. Tools: records, Lombok's @EqualsAndHashCode (configure carefully for JPA entities), and EqualsVerifier in unit tests to catch contract violations automatically.
Ravindra Wadile · · 0 likes