Java Collections Framework: HashMap Variants Explained

📘 Java Learning – Collections Framework Part 7: HashMap Variants (Hashtable, LinkedHashMap, IdentityHashMap, WeakHashMap) 🚀 Continuing my Java Collections series, this post focuses on different Map implementations and their practical behavior. 🔰 HashMap vs Hashtable HashMap • Not synchronized • Faster performance • Allows one null key and multiple null values Hashtable • Fully synchronized (thread-safe) • Slower due to thread waiting • Null key & null values not allowed 🧪 Example HashMap m = new HashMap(); m.put(1, "Java"); m.put(null, "Spring"); // allowed System.out.println(m); Hashtable ht = new Hashtable(); ht.put(1, "Java"); // ht.put(null, "Spring"); // NullPointerException 📌 Synchronized HashMap Map m = Collections.synchronizedMap(new HashMap()); 🔰 LinkedHashMap • Child class of HashMap • Maintains insertion order • Underlying structure: HashTable + LinkedList 🧪 Example LinkedHashMap lm = new LinkedHashMap(); lm.put(1, "Java"); lm.put(2, "Spring"); lm.put(3, "Boot"); System.out.println(lm); // Output: {1=Java, 2=Spring, 3=Boot} 📌 Use case Cache-like applications where: • Duplicates are not allowed • Insertion order must be preserved 🔰 IdentityHashMap • Same as HashMap except key comparison • Uses == instead of equals() • Comparison is reference-based 🧪 Example IdentityHashMap im = new IdentityHashMap(); Integer i1 = new Integer(10); Integer i2 = new Integer(10); im.put(i1, "Java"); im.put(i2, "Spring"); System.out.println(im); // Both entries stored (different references) 📌 Note: • HashMap → uses equals() • IdentityHashMap → uses == 🔰 WeakHashMap • Same as HashMap except GC behavior • Keys eligible for Garbage Collection • Entry removed if key has no external reference 🧪 Example WeakHashMap wm = new WeakHashMap(); Integer i = new Integer(10); wm.put(i, "Java"); i = null; System.gc(); System.out.println(wm); // Entry may be removed after GC runs 📌 Note: • HashMap → Map dominates GC • WeakHashMap → GC dominates Map ⭐ Key Takeaways • Hashtable → thread-safe but slow • LinkedHashMap → ordered Map • IdentityHashMap → reference-based keys • WeakHashMap → GC-friendly keys Choosing the right Map implementation is a design decision, not just an API choice 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #HashMap #LinkedHashMap #IdentityHashMap #WeakHashMap #Hashtable #JavaCollections #LearningJourney

To view or add a comment, sign in

Explore content categories