Why Overriding equals Without hashCode Breaks Java Collections
This article explains the contract of equals and hashCode in Java, shows what goes wrong when only equals is overridden, provides a vivid house‑ownership analogy, and offers practical guidelines and code examples for correctly overriding both methods.
When discussing equals and hashCode , people often recite the contract (reflexive, symmetric, transitive, consistent) but may not truly understand it.
1. What happens if you only override equals?
The default hashCode is derived from an object's memory address, so two objects are considered equal only when their addresses match. If you do not override hashCode, equal objects will have different hash codes, making hash‑based collections inefficient. equals compares addresses by default, which is slow for large collections, while a proper hash code enables fast element location.
2. Example
Imagine Xiao Wang owns two houses at different addresses. Using Object.equals tells us the houses are not owned by the same person because their addresses differ. After overriding equals, the comparison correctly identifies the same owner. However, when the property registry (a HashMap) checks the houses, it still relies on hashCode, leading to a mismatch unless hashCode is also overridden.
3. Summary
Unless you can guarantee that a class overriding equals will never be used in Set or Map, you must also override hashCode. If you cannot guarantee this, consider alternative designs (illustrated below).
4. How to override equals and hashCode
Override equals
Check this == other to see if they are the same reference.
Use instanceof to verify the same type.
Cast the parameter to the correct type.
Compare each relevant field for equality.
Example:
Override hashCode
The hashCode method should produce different hash values for unequal objects, typically based on the same fields used in equals. Two common approaches are:
Method 1: Use Objects.hash(...) provided by the JDK.
Method 2: Use Lombok’s @EqualsAndHashCode annotation on the class.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
