𝗛𝗼𝘄 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝗛𝗮𝗻𝗱𝗹𝗲𝘀 𝗻𝘂𝗹𝗹 𝗞𝗲𝘆 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹 𝗩𝗮𝗹𝘂𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮? After learning the internal working of HashMap, I was curious about one more thing: How does HashMap handle null? Here’s the simple explanation👇 1️⃣ HashMap allows one null key If you put a null key, Java always stores it in bucket 0. Why? Because Java skips hashing when the key is null. map.put(null, "value"); Only one null key is allowed. If you put another one, it simply updates the old value. --- 2️⃣ HashMap allows multiple null values Values are not used for hashing, so HashMap doesn’t care if values are null. map.put("a", null); map.put("b", null); Both are valid. --- 3️⃣ How lookup works for null key? When you call: map.get(null); HashMap directly checks bucket 0 and returns the value. No hashing. No equals check. --- 4️⃣ Why only HashMap allows null (not Hashtable)? Hashtable is older, synchronized, and does not allow null keys/values. HashMap was designed later with more flexibility. --- 💡 In short: 1 null key → stored in bucket 0 Any number of null values → allowed No hashing for null key Updating same null key replaces the value Small detail, but very important in interview #Java #HashMap #CollectionsFramework #BackendDevelopment #CodingConcepts #CleanCode #techieanky #javainterview
How HashMap handles null keys and values in Java
More Relevant Posts
-
🚀 𝐃𝐚𝐲 𝟗 — 𝐓𝐡𝐞 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐜𝐲 𝐓𝐫𝐚𝐩 𝐓𝐡𝐚𝐭 𝐁𝐫𝐨𝐤𝐞 𝐏𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 😱 Every Java dev has used a HashMap inside threads… But do you really know what happens when multiple threads modify it at once? 🤔 Let’s test your multithreading + collections depth 👇 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐮𝐭𝐢𝐥.*; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐌𝐚𝐩𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 { 𝐬𝐭𝐚𝐭𝐢𝐜 𝐌𝐚𝐩<𝐈𝐧𝐭𝐞𝐠𝐞𝐫, 𝐒𝐭𝐫𝐢𝐧𝐠> 𝐦𝐚𝐩 = 𝐧𝐞𝐰 𝐇𝐚𝐬𝐡𝐌𝐚𝐩<>(); 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) 𝐭𝐡𝐫𝐨𝐰𝐬 𝐈𝐧𝐭𝐞𝐫𝐫𝐮𝐩𝐭𝐞𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 { 𝐓𝐡𝐫𝐞𝐚𝐝 𝐭𝟏 = 𝐧𝐞𝐰 𝐓𝐡𝐫𝐞𝐚𝐝(() -> { 𝐟𝐨𝐫 (𝐢𝐧𝐭 𝐢 = 𝟎; 𝐢 < 𝟏𝟎𝟎𝟎; 𝐢++) { 𝐦𝐚𝐩.𝐩𝐮𝐭(𝐢, "𝐀" + 𝐢); } }); 𝐓𝐡𝐫𝐞𝐚𝐝 𝐭𝟐 = 𝐧𝐞𝐰 𝐓𝐡𝐫𝐞𝐚𝐝(() -> { 𝐟𝐨𝐫 (𝐢𝐧𝐭 𝐢 = 𝟏𝟎𝟎𝟎; 𝐢 < 𝟐𝟎𝟎𝟎; 𝐢++) { 𝐦𝐚𝐩.𝐩𝐮𝐭(𝐢, "𝐁" + 𝐢); } }); 𝐭𝟏.𝐬𝐭𝐚𝐫𝐭(); 𝐭𝟐.𝐬𝐭𝐚𝐫𝐭(); 𝐭𝟏.𝐣𝐨𝐢𝐧(); 𝐭𝟐.𝐣𝐨𝐢𝐧(); 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐌𝐚𝐩 𝐬𝐢𝐳𝐞: " + 𝐦𝐚𝐩.𝐬𝐢𝐳𝐞()); } } 💭 Question: What will the output be? 1️⃣ Always 2000 2️⃣ Sometimes less than 2000 3️⃣ May throw ConcurrentModificationException 4️⃣ Unpredictable / corrupted results 💬 Drop your guess 👇 Let’s see who still trusts HashMap under pressure 😏 #Java #Day9Challenge #HashMap #Multithreading #JavaTrickyQuestions #JavaDeveloper #Collections #Concurrency #CodingChallenge
To view or add a comment, sign in
-
🚀 Understanding HashMap in Java – The Heart of Fast Lookups! Have you ever wondered how Java’s HashMap gives such blazing-fast access to data? ⚡ Let’s break it down simply 👇 🧠 What is a HashMap? A HashMap in Java is a data structure that stores data in key-value pairs. It allows O(1) average time complexity for insertion, deletion, and lookup! 💡 How it works internally: 1️⃣ Every key is converted into a hash code using the hashCode() method. 2️⃣ The hash code decides which bucket (or index) the entry will be stored in. 3️⃣ If two keys map to the same bucket (collision), Java uses a LinkedList or Balanced Tree (after Java 8) to handle it. 4️⃣ When you call get(key), Java calculates the hash again, jumps directly to the bucket, and fetches the value — super fast! ⚙️ Key Features: ✅ No duplicate keys ✅ Allows one null key and multiple null values ✅ Not thread-safe (use ConcurrentHashMap for concurrency) 🔍 Quick Tip: Always override equals() and hashCode() together to avoid unexpected behavior in collections like HashMap. #Java #HashMap #Coding #BackendDevelopment #JavaInterview #SpringBoot #AdvanceJava
To view or add a comment, sign in
-
⚠️ ConcurrentModificationException — The Silent Iterator Killer in Java 🧠 You’ve definitely seen this one at least once 👇 java.util.ConcurrentModificationException It usually appears at the worst possible moment — inside a loop, in production logs, or during a batch job at 2 AM 😅 Let’s break down why this error actually happens and how to fix it. --- 🔹 1️⃣ Why This Error Happens Java collections like ArrayList and HashMap use fail-fast iterators. It means: > If you modify the collection while iterating, Java immediately throws an exception to protect you. Example 👇 for (String s : list) { list.add("new"); // ❌ ConcurrentModificationException } The iterator detects the structure change and says: “Stop! Someone is modifying this collection behind my back.” --- 🔹 2️⃣ Hidden Places Where This Happens Removing items inside a for-each loop ❌ Adding elements inside iteration ❌ Using Streams and modifying the source ❌ Multi-threaded modifications without synchronization ❌ Sometimes the code looks innocent, but the error still hits — because the collection was modified elsewhere 🤯 --- 🔹 3️⃣ How to Fix It (The Right Way) ✔ Use Iterator’s remove() Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("x")) it.remove(); // ✅ safe } ✔ Use CopyOnWriteArrayList (for read-heavy, write-light code) ✔ Use ConcurrentHashMap instead of HashMap (thread-safe updates) ✔ Collect items to remove first, then remove after the loop ✔ Use Stream filters instead of manual removal --- ⚡ The Takeaway ConcurrentModificationException isn’t a threading problem — it’s a modification-during-iteration problem. Java protects you from unpredictable behavior by failing fast 🚫 --- 💬 Your turn: Have you ever hit a ConcurrentModificationException in production? 👇 What was the strangest cause you discovered? #Java #Collections #Concurrency #BackendDevelopment #SoftwareEngineering #JavaDeveloper #CleanCode
To view or add a comment, sign in
-
💡 == Operator vs. .equals() Method: Why Context Matters in Java 🧐 When comparing two variables or objects in Java, the choice between the == operator and the .equals() method is critical. They perform two fundamentally different types of comparisons! 1. The == Operator (Identity Comparison) What it compares: The == operator always compares memory addresses (references). Primitives: When used with primitives (int, char, boolean, etc.), it checks if the values stored in those memory locations are identical. Example: (5 == 5) is true. Objects: When used with objects (including String), it checks if the two variables refer to the exact same object in the Heap memory. Example: (obj1 == obj2) is only true if they point to the same memory location (same object ID). 2. The .equals() Method (Content Comparison) What it compares: The .equals() method is used to check for content equality. It determines if two objects are meaningfully equal based on their data. Default Behavior: Since this method is inherited from the base Object class, its default behavior is the same as == (checking references). The Power of Overriding: For almost all custom classes and core classes (like String), this method is overridden. String overrides .equals() to check if the sequence of characters (the content) is identical. You must override it in your custom classes (like Employee) to define when two distinct objects are considered equal based on their field values (id, name, etc.). Always use .equals() when comparing the content of objects, and reserve == for comparing primitives or checking if two variables are references to the exact same physical object. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #OOP #ObjectEquality #SoftwareDevelopment #TechEducation
To view or add a comment, sign in
-
-
🔍 Why if(false) Compiles But while(false) Doesn't - A Java Quirk Explained 🤔💡 Most Java developers have seen this surprising behavior: But why does Java allow one and reject the other? ✅ 1. Java Allows Unreachable Code Inside if Statements 🟩🔓 The Java Language Specification explicitly allows unreachable code inside an if block: Even if the condition is a constant false, the code inside an if block is still legal. Why? Because this pattern is common for: 🛠️ Debugging 🚦 Feature flags 🛑 Temporarily disabling logic ❌ 2. Java Does Not Allow Unreachable Code Inside Loops 🔁🚫 But the rules change for loops According to JLS 14.12 & 14.21: If a loop condition is always false, the loop body becomes unreachable, and Java must throw a compile-time error. Why so strict? Because unreachable loops almost always mean a bug, not intentional behavior. Java’s compiler is designed to catch these issues early. 🎯 A small but fascinating detail that shows how deep and strict Java’s control-flow analysis really is. https://lnkd.in/de5-sXH7 #Java #JavaDeveloper #Javac #JavaTips #JavaProgramming #CodeQuality #CleanCode #SoftwareEngineering #BackendDevelopment #WritingBetterCode
To view or add a comment, sign in
-
-
🚀 Top Modern Java Features - Part 1🤔 🔥 Modern Java = Cleaner Code + More Power + Zero Boilerplate. 👇 1️⃣ LAMBDAS + STREAMS 🔹Java finally got functional, no loops, no clutter, just logic. 🔹E.g., list. stream().filter(x -> x > 5).forEach(System.out::println); 2️⃣ VAR (TYPE INFERENCE) 🔹Java got modern syntax, infers types automatically based on data value. 🔹E.g., var message = "Hello Java"; 3️⃣ TRY-WITH-RESOURCES 🔹Because you deserve auto-cleanup, no more closing connections manually. 🔹E.g., try (var conn = getConnection()) { } 4️⃣ TEXT BLOCKS (""" … """) 🔹Java said goodbye string chaos, Java’s multi-line strings keep it clean now. 🔹E.g., String html = """<html><body>Hello</body></html>"""; 5️⃣ OPTIONAL API 🔹The official cure for NullPointerException, safe, elegant, and expressive. 🔹E.g., Optional.ofNullable(user).ifPresent(System.out::println); 💬 Which feature changed the way you write Java? #Java #Java21 #ModernJava #Developers #Programming #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
💻 Mastering the Core of Java DTOs --> equals(), hashCode(), and compareTo() When building DTO (Data Transfer Object) classes in the data layer, these three methods silently ensure data consistency, uniqueness, and proper sorting. While implementing them, I realized, mastering a few core Java fundamentals makes a huge difference in how our applications behave. The three most important methods and interfaces that truly define object behavior are: 1️⃣ equals(Object obj) 🔸Defines how two objects are considered equal. 🔸Used by collections like Set or Map to prevent duplicates. 🔸Always ensure logical equality, not just reference equality. 2️⃣ hashCode() 🔸Returns a unique hash value used in hashing-based collections (HashMap, HashSet). 🔸If you override equals(), you must override hashCode() to maintain consistency. 3️⃣ compareTo(ClassName other) from Comparable<ClassName> 🔸Provides natural ordering for your objects. 🔸Enables sorting with Collections.sort() and TreeSet. Along with these, implementing these two most important interfaces 4️⃣ Serializable 🔸Makes the DTO transferable across different layers, APIs, or storing session data. Used as converted to a byte stream, allowing easy saving, caching, or sending over a network. Example: [for more refer post image] public class Member implements Serializable { … } 5️⃣ Comparable<T> 🔸Gives our objects a natural ordering for sorting and comparison. Example: [for more refer post image] public class Member implements Comparable<Member> { public int compareTo(Member other) { … } } These methods and interfaces ensure your objects are: ✅ Comparable (for sorting) ✅ Serializable (for transfer) ✅ Consistent (for hashing and equality) 📸 (Attached: My own Java DTO implementation of equals(), hashCode(), and compareTo() --> written in Vim on Linux 💻) Together, these create the foundation of reliable data-layer design, something that every backend developer must get right. I’m consistently sharpening my core Java skills to get placement for backend and enterprise-level development roles. Because strong fundamentals always make the best developers. Github: https://lnkd.in/deSpAU3K #JavaDeveloper #JavaProject #Java #SoftwareDevelopment #Programming
To view or add a comment, sign in
-
-
☕💥 The Most Confusing Java Error I’ve Ever Seen in Production 😅 There’s “normal” debugging… …and then there’s Java in Production, where the logs read like poetry written by chaos itself. Here’s one of those head-scratchers 👇 🧩 The Error: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer Seems simple, right? Except… it happened randomly, and only under high load. 🧠 The Root Cause: Turns out one thread was modifying a Map while another was reading it. The non-synchronized HashMap corrupted its internal state, mixing keys and values. So suddenly… "Hello" was where an Integer should’ve been. 🤯 ✅ The Fix: Replaced HashMap with ConcurrentHashMap. Added proper synchronization around shared mutable state. Added unit + concurrency tests (lesson learned the hard way). 💡 Moral of the story: Just because it compiles doesn’t mean it’s thread-safe. And just because it’s working now doesn’t mean it will at scale. ⚙️ Other confusing production gems: NoSuchBeanDefinitionException when bean actually exists → wrong package scan. OutOfMemoryError but heap looks fine → thread leak in a scheduled task. ClassNotFoundException only in prod → missing dependency in shaded JAR. Next time your logs whisper something mysterious, remember: Java doesn’t make mistakes — it just tests your patience 😅 #Java #SpringBoot #ProductionIssues #Debugging #DevHumor #DeveloperLife #Microservices #SoftwareEngineering #CodeLife #TechLife
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