How HashMap handles null keys and values in Java

𝗛𝗼𝘄 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝗛𝗮𝗻𝗱𝗹𝗲𝘀 𝗻𝘂𝗹𝗹 𝗞𝗲𝘆 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹 𝗩𝗮𝗹𝘂𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮? 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

To view or add a comment, sign in

Explore content categories