𝗪𝗵𝘆 𝗲𝗾𝘂𝗮𝗹𝘀() 𝗮𝗻𝗱 𝗵𝗮𝘀𝗵𝗖𝗼𝗱𝗲() 𝗠𝘂𝘀𝘁 𝗕𝗲 𝗢𝘃𝗲𝗿𝗿𝗶𝗱𝗱𝗲𝗻 𝗧𝗼𝗴𝗲𝘁𝗵𝗲𝗿 𝗶𝗻 𝗝𝗮𝘃𝗮 Many Java developers override equals(). But forget hashCode() And that can break your application in strange ways. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Imagine you create a class: 𝘤𝘭𝘢𝘴𝘴 𝘜𝘴𝘦𝘳 { 𝘚𝘵𝘳𝘪𝘯𝘨 𝘦𝘮𝘢𝘪𝘭; @𝘖𝘷𝘦𝘳𝘳𝘪𝘥𝘦 𝘱𝘶𝘣𝘭𝘪𝘤 𝘣𝘰𝘰𝘭𝘦𝘢𝘯 𝘦𝘲𝘶𝘢𝘭𝘴(𝘖𝘣𝘫𝘦𝘤𝘵 𝘰𝘣𝘫) { // 𝘭𝘰𝘨𝘪𝘤 𝘩𝘦𝘳𝘦 } } Everything seems fine. But when you use this object in a HashMap or HashSet, problems start appearing. Why? Java collections like HashMap use two steps: • 𝗵𝗮𝘀𝗵𝗖𝗼𝗱𝗲() → decide the bucket • 𝗲𝗾𝘂𝗮𝗹𝘀() → compare objects inside the bucket If you override only equals() and not hashCode(): Two objects may be equal but end up in different buckets. Result? Your map may behave incorrectly. Correct Rule • If you override equals(), • you must override hashCode(). Java’s contract requires both to be consistent. Many strange bugs in collections come from breaking this rule. Small details like this separate average Java developers from strong ones. Have you ever faced a bug because of equals() and hashCode()? #Java #Collections #Programming #SoftwareEngineering #JavaDeveloper #BackendDevelopment #CleanCode
Java equals() and hashCode() Must Be Overridden Together
More Relevant Posts
-
Most Java developers use this daily... but don't 𝘧𝘶𝘭𝘭𝘺 understand it. 𝑺𝒕𝒂𝒄𝒌 𝒗𝒔 𝑯𝒆𝒂𝒑 𝑴𝒆𝒎𝒐𝒓𝒚 𝒊𝒏 𝑱𝒂𝒗𝒂 If you're preparing for interviews or writing better Java code, this concept is a MUST. The problem? Most people just memorize the definitions. Let's change that. 𝑾𝒉𝒂𝒕 𝒊𝒔 𝑺𝒕𝒂𝒄𝒌 𝑴𝒆𝒎𝒐𝒓𝒚? Think of the Stack as your execution workspace. Every time a method is called, a new "stack frame" is created. This frame holds: Method calls Local variables References to objects 𝐊𝐞𝐲 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫𝐢𝐬𝐭𝐢𝐜𝐬: ->Works in LIFO (Last In First Out) manner ->Extremely fast ->Memory is automatically managed (as soon as the method finishes, the stack frame is gone) 𝑾𝒉𝒂𝒕 𝒊𝒔 𝑯𝒆𝒂𝒑 𝑴𝒆𝒎𝒐𝒓𝒚? The Heap is your storage room. All Java objects (including instance variables) live here. 𝐊𝐞𝐲 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫𝐢𝐬𝐭𝐢𝐜𝐬: ->Shared across the entire application ->Slower than stack access ->Managed by the Garbage Collector (this is where things get tricky!) 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝓟𝓮𝓻𝓼𝓸𝓷 𝓹 = 𝓷𝓮𝔀 𝓟𝓮𝓻𝓼𝓸𝓷(); Here's what's happening: ->𝓹 is the reference and it's stored in the Stack. ->𝓷𝓮𝔀 𝓟𝓮𝓻𝓼𝓸𝓷(); is the actual object and it's created in the Heap. Satyam Kumar #HarshCodes #Java #Programming #SoftwareEngineering #TechInterviews #CareerAdvice #MemoryManagement #codingblocks #Leetcode #codeforces
To view or add a comment, sign in
-
-
A few fundamental Java concepts continue to have a significant impact on system design, performance, and reliability — especially in backend applications operating at scale. Here are three that are often used daily, but not always fully understood: 🔵 HashMap Internals At a high level, HashMap provides O(1) average time complexity, but that performance depends heavily on how hashing and collisions are managed internally. Bucket indexing is driven by hashCode() Collisions are handled via chaining, and in Java 8+, transformed into balanced trees under high contention Resizing and rehashing can introduce performance overhead if not considered carefully 👉 In high-throughput systems, poor key design or uneven hash distribution can quickly degrade performance. 🔵 equals() and hashCode() Contract These two methods directly influence the correctness of hash-based collections. hashCode() determines where the object is stored equals() determines how objects are matched within that location 👉 Any inconsistency between them can lead to subtle data retrieval issues that are difficult to debug in production environments. 🔵 String Immutability String immutability is a deliberate design choice in Java that enables: Safe usage in multi-threaded environments Efficient memory utilization through the String Pool Predictable behavior in security-sensitive operations 👉 For scenarios involving frequent modifications, relying on immutable Strings can introduce unnecessary overhead — making alternatives like StringBuilder more appropriate. 🧠 Engineering Perspective These are not just language features — they influence: Data structure efficiency Memory management Concurrency behavior Overall system scalability A deeper understanding of these fundamentals helps in making better design decisions, especially when building systems that need to perform reliably under load. #Java #BackendEngineering #SystemDesign #SoftwareArchitecture #Performance #Engineering
To view or add a comment, sign in
-
🚀 HashMap vs ConcurrentHashMap in Java If you're working with multi-threaded applications, knowing the difference is very important. HashMap 1. Not thread-safe 2. Multiple threads can modify data → may cause data corruption 3. Faster in single-threaded environments 4. Allows one null key and multiple null values ConcurrentHashMap 1. Thread-safe 2. Uses segment-level locking (Java 7) / CAS + synchronized (Java 8+) 3. Multiple threads can read/write safely 4. Does NOT allow null key or null values 5. Slightly slower than HashMap due to synchronization When to use what? 1. Single-threaded → Use HashMap 2. Multi-threaded → Use ConcurrentHashMap 3. Read-heavy concurrent apps → ConcurrentHashMap is best Simple Example Map<String, Integer> map = new HashMap<>(); Map<String, Integer> cmap = new ConcurrentHashMap<>(); Rule of Thumb HashMap for speed, ConcurrentHashMap for thread safety. 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #BackendDevelopment #SpringBoot #JavaCollections #ConcurrentHashMap #SoftwareEngineering
To view or add a comment, sign in
-
-
Java Streams – Simplifying Data Processing 🚀 📌 Java Stream API is used to process collections (like List, Set) in a declarative and functional style. Before Java 8, processing data required a lot of boilerplate code. With Streams, operations become clean, concise, and powerful. 📌 Advantages: ✔ Less code. ✔ Better performance (due to lazy evaluation). ✔ Easy data transformation. 📌 Limitations: • Harder to debug. • Can reduce readability if overused. 📌 Types of Streams 1️⃣ Sequential Stream: Processes data using a single thread (default). 2️⃣ Parallel Stream: Splits tasks across multiple threads. ✔ Improves performance for large datasets 📌 Thread usage (approx): Available processors - 1 . 📌 Stream Operations 1️⃣ Intermediate Operations (Lazy) ⚙️ ✔ Return another stream ✔ Used to build a processing pipeline ✔ Do not execute immediately ✔ Execution starts only when a terminal operation is called. Examples: filter(), map(), flatMap(), distinct(), sorted(), limit(), skip() . 2️⃣ Terminal Operations 🎯 ✔ Trigger the execution of the stream. ✔ Return a final result (non-stream) . ✔ Can be called only once per stream. Examples: forEach(), collect(), count(), findFirst(). Grateful to my mentor Suresh Bishnoi Sir for explaining Streams with such clarity and practical depth . If this post added value, consider sharing it and connect for more Java concepts. #Java #JavaStreams #StreamAPI #CoreJava #JavaDeveloper #BackendDevelopment #FunctionalProgramming #InterviewPreparation #SoftwareEngineering 🚀
To view or add a comment, sign in
-
🧩 equals() vs hashCode() in Java In Java, the equals() and hashCode() methods define how objects are compared and stored within hash-based collections. The equals() method determines logical equality between two objects by comparing their state or content, while hashCode() generates an integer representation used by hash-based data structures such as HashMap, HashSet, and Hashtable to efficiently organize and retrieve objects. The Java contract requires that if two objects are equal according to equals(), they must return the same hashCode(). This consistency ensures predictable behavior in collections that rely on hashing for fast lookups. When this contract is violated, it can lead to subtle bugs such as duplicate entries in sets, failed retrievals from maps, or degraded performance due to excessive hash collisions. Adhering to this contract is essential for building reliable, scalable, and performant systems. Proper implementations maintain logical consistency, support efficient data structures, and ensure that domain objects behave correctly within distributed and enterprise-grade Java applications. #Java #JVM #ObjectOrientedProgramming #EqualsHashCode #JavaCollections #SoftwareArchitecture #BackendEngineering #CleanCode #EnterpriseJava #SpringBoot #Microservices #SystemDesign #CloudNative #DistributedSystems #JavaDeveloper #EngineeringBestPractices #ScalableSystems
To view or add a comment, sign in
-
-
Are you still creating threads manually in Java? Previously I covered Thread, Runnable, and Callable, now I have dived deeper into ExecutorService, Thread Pools, and CompletableFuture—the tools we actually use in real-world systems. In this blog, I’ve explained: ✓ What Thread Pools are and why they matter ✓ How to use ExecutorService for better performance & control ✓ How CompletableFuture enables clean, non-blocking async code ✓ Practical Java examples you can apply immediately → Check it out and let me know your thoughts! #Java #Multithreading #Concurrency #BackendDevelopment #SpringBoot #SoftwareEngineering
Mastering Java Multithreading (Part 2): Thread Pools, ExecutorService & CompletableFuture medium.com To view or add a comment, sign in
-
💡 How HashMap Works Internally in Java HashMap stores data in key–value pairs, but internally it uses a hashing mechanism. 🔹 Step 1: Hash Calculation When you insert a key, Java calculates a hash code using hashCode(). 🔹 Step 2: Bucket Index The hash value determines the bucket index in an internal array. 🔹 Step 3: Store Entry The key–value pair is stored in that bucket. 🔹 Step 4: Collision Handling If two keys map to the same bucket: • Java uses LinkedList (before Java 8) • Balanced Tree (Red-Black Tree) if the bucket becomes large (Java 8+) 📌 Flow: Key → hashCode() → Bucket Index → Store Entry Understanding this helps explain why HashMap operations are O(1) on average. #Java #JavaCollections #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
🔹 ModelMapper vs ObjectMapper in Java – What’s the Difference? Many Java developers get confused between ModelMapper and ObjectMapper because both deal with data transformation. But their purposes are different. ModelMapper ModelMapper is used to map one Java object to another Java object. It is commonly used in Spring Boot applications to convert Entity objects to DTOs and vice versa. This helps keep the application layers clean and maintainable. Example use case: UserEntity → UserDTO UserRequest → UserEntity ObjectMapper ObjectMapper is part of the Jackson library and is used for JSON serialization and deserialization. It converts Java objects to JSON and JSON to Java objects, which is very useful when working with REST APIs. Example use case: JSON → Java Object Java Object → JSON Key Difference ModelMapper → Object to Object mapping ObjectMapper → JSON to Object conversion Understanding when to use each of these tools helps build cleaner and more efficient backend applications. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
🚀 Day 8 – Prepare with Pankaj Most developers say they know HashMap… But very few understand what happens internally in Java 8 👀 Let’s go beyond basics and uncover the real magic 🔥 🧠 HashMap Internal Working (Java 8) ✔️ Data stored in array of nodes (buckets) ✔️ Index calculated using: 👉 index = (n - 1) & hash ✔️ Collision handling: ➡️ Before Java 8 → LinkedList ➡️ After Java 8 → LinkedList → Red-Black Tree (if size > 8) ✔️ Why Treeify? 👉 Improves worst case from O(n) → O(log n) ✔️ Resize happens when: 👉 Load Factor (0.75 default) is exceeded ✔️ Rehashing: 👉 New bigger array created 👉 Old entries redistributed ⚡ Hidden Concepts Most People Miss: 🔸 Why power of 2 array size? 🔸 How hash spreading works? 🔸 When tree converts back to LinkedList? (Untreeify < 6) 💬 If you truly understand this, you’re already ahead of 80% Java developers. #Java #Backend #PrepareWithPankaj #InterviewPrep #JavaInternals #SpringBoot#Java #CoreJava #JavaDeveloper #BackendDeveloper #SoftwareEngineer #JavaInternals #HashMap #DataStructures #CodingInterview #TechInterview #SystemDesign #SpringBoot #DevelopersLife #CodingJourney #LearnToCode #100DaysOfCode #Programmers #TechCommunity #DevelopersIndia #LinkedInLearning #CareerGrowth #JobSwitch #InterviewPreparation #PrepareWithPankaj #CodingTips #TechContent #SoftwareDevelopment #ProgrammingLife #CodeNewbie #ITJobs #JavaLearning
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Recently got to know about this through my Team lead, and I was very shocked since I was unaware about this and thankfully I have not missed this in the production code 😂😅