Java Bug: Overriding equals() Without hashCode() Can Break Your Entire Application This is one of the most common — and dangerous — mistakes I still encounter in Java backend codebases. Seen recently during a Spring Boot audit: The developer implemented equals() correctly… but forgot hashCode(). 👉 The result? Silent, unpredictable bugs in production. ❌ Vulnerable Code Example public class User { private String email; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return email.equals(user.email); } } 💥 Why This Breaks Things Collections like HashSet, HashMap, and ConcurrentHashMap rely on hashCode(), not just equals(). If two objects are equal but have different hash codes: HashSet may allow duplicates HashMap may fail to retrieve values Cache layers become inconsistent Bugs appear randomly and are hard to reproduce 🧠 Real-World Example Set<User> users = new HashSet<>(); users.add(new User("test@mail.com")); users.add(new User("test@mail.com")); System.out.println(users.size()); // Can return 2 🤯 ✅ The Fix (Always Apply This Rule) 👉 If you override equals(), you MUST override hashCode() @Override public int hashCode() { return Objects.hash(email); } 🔥 What I’ve Seen in Production Duplicate users in databases Broken caching layers Inconsistent business logic Intermittent bugs that waste hours of debugging 🛡️ Best Practice Never rely on equals() alone. Always respect the equals/hashCode contract defined in Java. 🚨 Quick Question How many of your domain classes correctly implement both equals() and hashCode()? #Java #JavaDev #SpringBoot #Backend #SoftwareEngineering #CleanCode #Programming #Debugging #TechDebt #Performance
equals() without hashCode() is a silent killer in production.
just use records or lombok
Object / object ?
Maybe you can compare the hashcode of the two object in your equals()...