𝗛𝗼𝘄 𝗱𝗼𝗲𝘀 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘄𝗼𝗿𝗸 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆? 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗿𝗲𝗲𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻 𝘁𝗵𝗮𝘁 𝘄𝗮𝘀 𝗮𝗱𝗱𝗲𝗱 𝗶𝗻 𝗝𝗮𝘃𝗮 𝟴? Under the hood, HashMap is not just a simple key-value store: → Array of buckets → Linked List (for collisions) → Red-Black Tree (Java 8+ optimization) 𝗪𝗵𝗮𝘁 𝗿𝗲𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗼𝗻 𝗽𝘂𝘁()? Hash is calculated (with bit mixing) Bucket index is derived using (n-1) & hash Collision? Before Java 8 → Linked List (O(n)) After Java 8 → Converts to Tree (O(log n)) 𝗧𝗿𝗲𝗲𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻 (𝘁𝗵𝗲 𝗴𝗮𝗺𝗲 𝗰𝗵𝗮𝗻𝗴𝗲𝗿) Bucket size > 8 (A single bucket (bin) holds more than 8 entries.) AND capacity ≥ 64 (The total HashMap capacity is at least 64.) Only then → Linked List → Red-Black Tree Otherwise → resize instead 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗺𝗮𝘁𝘁𝗲𝗿𝘀 𝗶𝗻 𝗿𝗲𝗮𝗹 𝘀𝘆𝘀𝘁𝗲𝗺𝘀 Bad hashing or high collisions can turn your O(1) into O(n) In high throughput systems (100k+ rpm), this = → latency spikes → CPU increase → unpredictable performance 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 HashMap = Array + LinkedList + Tree (conditionally) Performance depends heavily on: ▸ hashCode() ▸ load factor ▸ resizing behavior 👉 Full deep dive (with diagrams & internals) - link in the comments section. Try out Java-related quizzes and solidify learning - https://lnkd.in/gzFmANXT #Java #HashMap #Map #SystemDesign #Backend #DataStructures #InterviewPrep #Codefarm
How HashMap works internally in Java
More Relevant Posts
-
HashMap Deep Dive (Beyond Basics) Most people use HashMap. Very few understand how it actually works internally. Key Concepts: - Array of Nodes (Bucket-based storage) - Hashing & Index calculation - Collision handling (LinkedList → Tree after threshold) - Load Factor & Rehashing - Time Complexity: - Average → O(1) - Worst → O(log n) (after Java 8) Interview-Level Insight Why Java 8 introduced Tree instead of LinkedList? How hashCode() & equals() impact performance? When does rehashing happen? Why initial capacity matters? Code Insight Map<Integer, String> map = new HashMap<>(); map.put(1, "A"); map.put(2, "B"); map.put(17, "C"); // Collision example (same bucket possible) // Internal flow: int hash = key.hashCode(); int index = (n - 1) & hash; Interview Gold If multiple keys land in the same bucket: - Before Java 8 → LinkedList (O(n)) - After Java 8 → Balanced Tree (O(log n)) This is a favorite interview discussion topic. Challenge for You Can you explain why HashMap is NOT thread-safe? What happens if two threads write simultaneously? Drop your answers below #Java #DSA #InterviewPreparation #SoftwareEngineering #CodingJourney #SystemDesign #Multithreading #JavaDeveloper
To view or add a comment, sign in
-
Solved Sort Characters By Frequency -> LeetCode Medium, String + HashMap in Java. What I built: Count frequency of each character using HashMap, convert it to a list, sort by frequency in decreasing order, then build the result using StringBuilder. Problem I faced: First I tried storing frequencies in an array and sorting it , but that was O(n log n). Switched to HashMap for frequency counting which brings sorting down to O(k log k) where k is number of unique keys. Since max ASCII characters are 128, it's basically O(1). The part I got stuck on -> I didn't know how to sort a HashMap. Googled it, found out HashMap can't be sorted directly. So converted it to a List of entries and sorted that using a lambda comparator. Took help for two things only — how to sort a HashMap, and the syntax for the comparator. Logic was mine. Still learning HashMap operations properly, but slowly getting comfortable . Open to better approaches! Github: https://lnkd.in/gBgb3jAK #DSA #Java #LeetCode #HashMap #Strings #LearningInPublic
To view or add a comment, sign in
-
🚀 How HashMap Works Internally (In Simple Words) Most developers use HashMap daily… But very few actually understand what happens behind the scenes. 👀 Let’s break it down 👇 👉 1️⃣ Hashing – The Core Idea When you put a key-value pair into a HashMap: 👉 Java converts the key into a number using a hash function (hashCode()). Think of it like: 🔑 Key → 🔢 Hash → 📦 Bucket 👉 2️⃣ Bucket Storage HashMap has an array of buckets. The hash determines which bucket your data goes into. 👉 Index = hash % array size 👉 3️⃣ Collision Handling (Important 🔥) Sometimes multiple keys get the same bucket 😱 This is called a collision HashMap handles it using: ✔️ Linked List (before Java 8) ✔️ Balanced Tree (after Java 8, for better performance) 👉 4️⃣ Retrieval (get operation) When you do map.get(key) 👉 Same hashing process happens Then: ✔️ Go to the correct bucket ✔️ Search inside (list/tree) ✔️ Match using equals() 👉 5️⃣ Performance ⚡ Average time complexity: ✔️ Put → O(1) ✔️ Get → O(1) Worst case (many collisions): ❌ O(n) → improved to O(log n) in Java 8 👉 6️⃣ Load Factor & Resizing When HashMap gets too full: 👉 It resizes (doubles capacity) Default load factor = 0.75 Meaning: resize when 75% full 💡 Real Insight: A good hashCode() implementation = better performance 🚀 🔥 Final Thought HashMap looks simple from outside… But internally it’s a smart combination of: ➡️ Arrays ➡️ Hashing ➡️ Linked Lists / Trees 💬 Have you ever faced HashMap collision issues? #Java #DSA #Programming #BackendDevelopment #InterviewPrep
To view or add a comment, sign in
-
-
𝐯𝐚𝐫 𝐤𝐞𝐲𝐰𝐨𝐫𝐝 𝐢𝐧 𝐉𝐚𝐯𝐚 Introduced in Java 10, the var reserved type name is a game-changer for reducing boilerplate code—but it comes with specific "rules of the road." Is it a keyword? Technically, no! It’s a 𝐫𝐞𝐬𝐞𝐫𝐯𝐞𝐝 𝐭𝐲𝐩𝐞 𝐧𝐚𝐦𝐞 that uses 𝐓𝐲𝐩𝐞 𝐈𝐧𝐟𝐞𝐫𝐞𝐧𝐜𝐞 to automatically detect data types based on the context. Here is a quick cheat sheet on the Dos and Don'ts: 𝐖𝐡𝐞𝐧 𝐭𝐨 𝐮𝐬𝐞 '𝐯𝐚𝐫': 𝐋𝐨𝐜𝐚𝐥 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬: Use it inside methods, blocks, or constructors. 𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝 𝐃𝐚𝐭𝐚 𝐓𝐲𝐩𝐞𝐬: Works for int, double, String, etc., as long as an initializer is present. 𝐂𝐥𝐞𝐚𝐧𝐢𝐧𝐠 𝐮𝐩 𝐆𝐞𝐧𝐞𝐫𝐢𝐜𝐬: Turn long declarations into clean, readable lines. 𝐖𝐡𝐞𝐫𝐞 '𝐯𝐚𝐫' 𝐢𝐬 𝐍𝐎𝐓 𝐚𝐥𝐥𝐨𝐰𝐞𝐝: 𝐈𝐧𝐬𝐭𝐚𝐧𝐜𝐞 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬: You cannot use it for class-level fields. 𝐌𝐢𝐬𝐬𝐢𝐧𝐠 𝐈𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐞𝐫𝐬: You can't just declare var x;. The compiler needs to see the value immediately. 𝐍𝐮𝐥𝐥 𝐕𝐚𝐥𝐮𝐞𝐬: var x = null; won't work because the compiler can't infer a type from null. 𝐋𝐚𝐦𝐛𝐝𝐚𝐬: These need an explicit target type, so var is a no-go here. 𝐌𝐞𝐭𝐡𝐨𝐝 𝐒𝐩𝐞𝐜𝐬: It cannot be used for method parameters or return types. 𝐓𝐡𝐞 𝐆𝐨𝐥𝐝𝐞𝐧 𝐑𝐮𝐥𝐞: var is meant to improve 𝐫𝐞𝐚𝐝𝐚𝐛𝐢𝐥𝐢𝐭𝐲. If using it makes the code harder to understand, stick to explicit types! Special thanks to Syed Zabi Ulla Sir for the clear breakdown and guidance on these core Java concepts! #Java #Programming #CodingTips #BackendDevelopment #Java10 #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
-
If your class name looks like CoffeeWithMilkAndSugarAndCream… you’ve already lost. This is how most codebases slowly break: You start with one clean class. Then come “small changes”: add logging add validation add caching So you create: a few subclasses… then a few more or pile everything into if-else Now every change touches existing code. And every change risks breaking something. That’s not scaling. That’s slow decay. The Decorator Pattern fixes this in a simple way: Don’t modify the original class. Wrap it. Start with a base object → then layer behavior on top of it. Each decorator: adds one responsibility doesn’t break existing code can be combined at runtime No subclass explosion. No god classes. No fragile code. Real-world example? Java I/O does this everywhere: you wrap streams on top of streams. The real shift is this: Stop thinking inheritance. Start thinking composition. Because most “just one more feature” problems… are actually design problems. Have you ever seen a codebase collapse under too many subclasses or flags? #DesignPatterns #LowLevelDesign #SystemDesign #CleanCode #Java #SoftwareEngineering #OOP Attaching the decorator pattern diagram with a simple example.
To view or add a comment, sign in
-
-
#Post11 In the previous post(https://lnkd.in/dynAvNrN), we saw how to create threads in Java. Now let’s talk about a problem. If creating threads is so simple… why don’t we just create a new thread every time we need one? Let’s say we are building a backend system. For every incoming request/task, we create a new thread: new Thread(() -> { // process request }).start(); This looks simple. But this approach breaks very quickly in real systems because of below mentioned problems. Problem 1: Thread creation is expensive Creating a thread is not just creating an object. It involves: • Allocating memory (stack) • Registering with OS • Scheduling overhead Creating thousands of threads = performance degradation Problem 2: Too many threads → too much context switching We already saw this earlier(https://lnkd.in/dYG3v-vb). More threads does NOT mean more performance. Instead: • CPU spends more time switching • Less time doing actual work Problem 3: No control over thread lifecycle When you create threads manually: • No limit on number of threads • No reuse • Hard to manage failures This quickly becomes difficult to manage as the system grows. So what’s the solution? Instead of creating threads manually: we use something called the Executor Framework. In simple words consider the framework to be like: Earlier, we were manually hiring a worker (thread) for every task. With Executor, we have a team of workers (thread pool), and we just assign tasks to them. Key idea Instead of: Creating a new thread for every task We do: Submit tasks to a pool of reusable threads This is exactly what Java provides using: Executor Framework Key takeaway Manual thread creation works for learning, but does not scale in real-world systems. Thread pools help: • Control number of threads • Reduce overhead • Improve performance We no longer manage threads directly — we delegate that responsibility to the Executor Framework. In the next post, we’ll see how Executor Framework works and how to use it in Java. #Java #Multithreading #Concurrency #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
⏳Day 29 – 1 Minute Java Clarity – HashMap Deep Dive + Internal Working How does HashMap actually store data? 🤔 📌 What is HashMap? It's a key-value pair data structure backed by an array of buckets (Node[]) internally. 📌 Internal Working: Map<String, Integer> map = new HashMap<>(); map.put("Alice", 90); // 1. "Alice".hashCode() called // 2. Index calculated (e.g., Index 3) // 3. Stored in Bucket 3 📌 Key Internals at a Glance: Default Capacity: 16 buckets. Load Factor: 0.75 (Resizes when 75% full). Threshold: If a bucket exceeds 8 entries, it transforms from a LinkedList into a Red-Black Tree (Java 8+). ⚠️ The Interview Trap: What happens when two keys have the same hashCode? 👉 This is a collision. They are stored in the same bucket. 👉 Java 7: Uses a LinkedList (Chaining). 👉 Java 8+: Uses a Tree to keep performance at O(log n) instead of O(n). 💡 Real-world Analogy: Think of a Mailroom. hashCode() is the building number (gets you to the right spot fast). equals() is the name on the envelope (finds the exact person). ✅ Quick Summary: ✔ hashCode() decides the bucket. ✔ equals() finds the exact key in case of collisions. ✔ Not thread-safe — use ConcurrentHashMap for multi-threading. 🔹 Next Topic → HashMap vs HashTable vs ConcurrentHashMap Did you know Java 8 uses Red-Black Trees to prevent "Hash Denial of Service" attacks? Drop 🔥 if this was new to you! #Java #HashMap #JavaCollections #CoreJava #BackendDeveloper #1MinuteJavaClarity #100DaysOfCode #DataStructures
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗝𝗮𝘃𝗮 𝘀𝘄𝗶𝘁𝗰𝗵 𝘀𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 𝘁𝘂𝗿𝗻𝗲𝗱 𝟯𝟬 𝘁𝗵𝗶𝘀 𝘆𝗲𝗮𝗿 Here's the short version: What started as a C-style branching construct is now a declarative data-matching engine — and the JVM internals behind it are genuinely fascinating. What I learned going deep on this: → Early switch relied on jump tables — fast, but fall-through bugs were silent and destructive → Java added definite assignment rules, preventing uninitialized variables from slipping through → The JVM picks between tableswitch (O(1)) and lookupswitch (O(log n)) based on how dense your cases are → String switching since Java 7 uses hashCode + equals internally — it's not magic, it's two passes → Java 14 made switch an expression, which killed fall-through at the language level → Modern Java (21+) adds pattern matching with type binding and null handling — code reads like a description of data → invokedynamic enables runtime linking, replacing rigid compile-time dispatch tables → Java 25 enforces unconditional exactness in type matching — no more silent data loss • The real shift isn't syntax. It's the question switch answers. Old: "Where should execution go?" New: "What is the shape of this data?" That's not just a feature upgrade. That's a change in how you think about branching. Which of these surprised you most? Drop it in the comments. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareEngineering #JVM #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
🚀 DAY 98/150 — TOP K FREQUENT ELEMENTS! 🔥📊 Day 98 of my 150 Days DSA Challenge in Java and today I solved a very popular interview problem that combines HashMap + Heap (Priority Queue) 💻🧠 📌 Problem Solved: Top K Frequent Elements 📌 LeetCode: #347 📌 Difficulty: Medium 🔹 Problem Insight The task is to return the k most frequent elements in an array. 👉 Instead of sorting the entire array, we need an efficient way to track frequencies and extract top elements. 🔹 Approach Used I used HashMap + Min Heap: • First, count frequency of each element using a HashMap • Then, maintain a Min Heap of size k based on frequency • If heap size exceeds k → remove the least frequent element ✔️ Finally, heap contains the k most frequent elements ⏱ Complexity Time Complexity: O(n log k) Space Complexity: O(n) 🧠 What I Learned • Frequency-based problems often use HashMap • Heap helps optimize Top K problems efficiently • Avoid full sorting when only top elements are required 💡 Key Takeaway This problem taught me: How to combine counting + priority queue How to optimize from O(n log n) → O(n log k) Importance of choosing the right data structure 🌱 Learning Insight Now I can clearly recognize: 👉 Top K Pattern → Use Heap 👉 Frequency Problem → Use HashMap ✅ Day 98 completed 🚀 52 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gtDixfZY 💡 Don’t sort everything — just focus on what matters. #DSAChallenge #Java #LeetCode #Heap #HashMap #TopK #PriorityQueue #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
𝑯𝒂𝒔𝒉𝑴𝒂𝒑 𝒍𝒐𝒐𝒌𝒔 𝒔𝒊𝒎𝒑𝒍𝒆 𝒇𝒓𝒐𝒎 𝒐𝒖𝒕𝒔𝒊𝒅𝒆 𝑩𝒖𝒕 𝒊𝒏𝒕𝒆𝒓𝒏𝒂𝒍𝒍𝒚, 𝒕𝒉𝒆𝒓𝒆’𝒔 𝒂 𝒍𝒐𝒕 𝒉𝒂𝒑𝒑𝒆𝒏𝒊𝒏𝒈 𝒕𝒉𝒂𝒕 𝒎𝒐𝒔𝒕 𝒐𝒇 𝒖𝒔 𝒎𝒊𝒔𝒔 𝑾𝒆 𝒂𝒍𝒍 𝒖𝒔𝒆 𝑯𝒂𝒔𝒉𝑴𝒂𝒑 𝑩𝒖𝒕 𝒉𝒂𝒗𝒆 𝒚𝒐𝒖 𝒆𝒗𝒆𝒓 𝒕𝒓𝒊𝒆𝒅 𝒆𝒙𝒑𝒍𝒂𝒊𝒏𝒊𝒏𝒈 𝒊𝒕𝒔 𝒊𝒏𝒕𝒆𝒓𝒏𝒂𝒍 𝒘𝒐𝒓𝒌𝒊𝒏𝒈 𝒘𝒊𝒕𝒉𝒐𝒖𝒕 𝒈𝒆𝒕𝒕𝒊𝒏𝒈 𝒔𝒕𝒖𝒄𝒌 ? 🔍 𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥 𝐖𝐨𝐫𝐤𝐢𝐧𝐠 𝐨𝐟 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 ➡️ 𝐖𝐡𝐞𝐧 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 𝐢𝐬 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 ▪️An array of 16 buckets is created (default capacity) ▪️Each bucket acts like a LinkedList ➡️ 𝐖𝐡𝐞𝐧 𝐰𝐞 𝐢𝐧𝐬𝐞𝐫𝐭 (𝐤𝐞𝐲, 𝐯𝐚𝐥𝐮𝐞) map.put(key, value); 📃 Step 1: Hash Calculation ▪️ First, hashCode() is generated for the key 📃 Step 2: Index Calculation ▪️ Index is calculated using: index = (n - 1) & hashCode "n" = size of array (default 16) Result will be between 0 to 15 📃 Step 3: Storing in Bucket ▪️ This index decides which bucket to store data in ▪️Each bucket stores data as: (key, value) → (key, value) (LinkedList) 🔁 𝐖𝐡𝐚𝐭 𝐢𝐟 𝐛𝐮𝐜𝐤𝐞𝐭 𝐚𝐥𝐫𝐞𝐚𝐝𝐲 𝐡𝐚𝐬 𝐝𝐚𝐭𝐚(𝐂𝐨𝐥𝐥𝐢𝐬𝐢𝐨𝐧) ⛓️ HashMap checks for existing keys ▫️Uses equals() method ▫️Compares new key with existing keys ➡️ 𝐏𝐨𝐬𝐬𝐢𝐛𝐥𝐞 𝐂𝐚𝐬𝐞𝐬 : 1️⃣ If no key matches ▪️ New (key, value) is added 2️⃣ If key matches ▪️Old value is overridden ⚠️ 𝐈𝐦𝐩𝐨𝐫𝐭𝐚𝐧𝐭 𝐈𝐧𝐬𝐢𝐠𝐡𝐭 ➡️ A single bucket can hold multiple key-value pairs ➡️ Commonly up to 7 nodes in LinkedList, after that it may convert into a Tree (in newer Java versions) 🔄 𝐑𝐞𝐬𝐢𝐳𝐢𝐧𝐠 (𝐑𝐞𝐡𝐚𝐬𝐡𝐢𝐧𝐠) When 75% (3/4) of buckets are filled ▫️ Capacity increases from 16 → 32 ▫️ New array is created ▫️ All existing elements are rehashed & moved 🔖 𝐊𝐞𝐲 𝐏𝐨𝐢𝐧𝐭𝐬 ▫️ Default capacity → 16 ▫️ Uses LinkedList (or Tree in newer versions) ▫️ Uses equals() to compare keys ▫️ Uses bitwise AND for index calculation 💭 One Line Summary ➡️ HashMap is not random — it’s intelligently organized #Java #HashMap #JavaDeveloper #DataStructures #Programming #TechJourney #LearnBySharing #InterviewPrep #BackendDevelopment 🚀
To view or add a comment, sign in
More from this author
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