Most developers say HashMap operations are O(1). That’s not always true. And this misunderstanding shows up in interviews and real systems. Let’s break down what actually happens inside a HashMap: Internally, HashMap uses an array of buckets: Node<K, V>[] table (default size = 16) Each bucket stores a structure like: class Node<K, V> { int hash; K key; V value; Node<K, V> next; } When you insert a key-value pair: 1.Hash value is calculated from the key 2.Bucket index is found using: hash % capacity 3.Entry is placed in that bucket Now the critical part: What if multiple keys map to the same bucket? 👉 Collision happens Entries are stored as a LinkedList using the next pointer If collisions increase → performance degrades Worst case: 👉 All keys land in same bucket → O(n) To handle this, Java introduced optimizations: Load Factor = 0.75 → When no. Entries > capacity * 0.75 → rehashing happens → Capacity doubles → reduces collisions Treeify Threshold = 8 → If a bucket has more than 8 entries → LinkedList converts into Red-Black Tree Now complexity improves: 👉 From O(n) → O(log n) So the reality is: Best case → O(1) Worst case → O(n) Optimized worst case → O(log n) Challenge: So what is Internal structure of LinkedHashMap ? Let’s see how you think about internal design 👇 #Java #BackendDevelopment #SoftwareEngineering #SystemDesign #HashMap #JavaDeveloper
Mitul Ranpariya’s Post
More Relevant Posts
-
HashMap Internal Working — How put() Actually Works 🔍 When you write: Map<String, String> map = new HashMap<>(); map.put("name", "Java"); Let’s see what happens internally 👇 Step 1 → hashCode() ▸ HashMap calculates hash of the key ▸ Example: "name".hashCode() → 3373707 Step 2 → Index Calculation ▸ index = hash & (n - 1) ▸ Determines the bucket where data will be stored Step 3 → Store Entry in Bucket ▸ If bucket is empty → stores Entry(key, value) directly ▸ If bucket already has elements → collision handling happens → equals() checks keys → Same key → value replaced → Different key → added to LinkedList Step 4 → Java 8 Optimization ⚡ ▸ If bucket size becomes > 8 nodes ▸ LinkedList converts into Red-Black Tree ▸ Search complexity improves: O(n) → O(log n) Example: map.put("name", "Java"); map.put("name", "Python"); // replaces old value map.get("name"); // returns "Python" #Java #JVM #HashMap #Collections #JavaDeveloper #SpringBoot
To view or add a comment, sign in
-
-
I've used HashMap in every Spring Boot service I've written for 1 year. I was reading an article on DEV Community about HashMap vs ConcurrentHashMap. It made me realize 3 situations where HashMap was quietly the wrong choice in my own code. Nobody talks about this. Every post explains how HashMap works. Nobody explains when to stop using it. Here's what I learned: Situation 1 — Multiple threads accessing the same map HashMap is not thread safe. Period. In a Spring Boot service, your beans are singletons by default. If two threads hit the same endpoint simultaneously and both modify a shared HashMap — you get data corruption, infinite loops during rehashing, or silent data loss. No exception. No warning. Just wrong data in production. What to use instead → ConcurrentHashMap It locks at bucket level, not the entire map. Reads are completely lock free. Writes only lock the specific bucket being modified. Situation 2 — You need atomic check then act operations This is the one most developers miss completely. // This looks safe. It is not. if (!map.containsKey(key)) { map.put(key, value); } Two threads can both pass the containsKey check simultaneously and both execute put — overwriting each other's data. What to use instead → ConcurrentHashMap.computeIfAbsent() map.computeIfAbsent(key, k -> value); One atomic operation. Zero race conditions. Situation 3 — High frequency reads with occasional writes For scenarios with 90% reads and 10% writes — like a configuration cache or reference data store — even ConcurrentHashMap's bucket locking adds unnecessary overhead. What to use instead → ReadWriteLock with HashMap or a purpose built cache like Caffeine. Reads acquire shared lock simultaneously. Writes acquire exclusive lock only when updating. Most production bugs don't come from using the wrong algorithm. They come from using the right data structure in the wrong environment. Have you ever hit a production issue caused by HashMap in a multithreaded context? #Java #SpringBoot #HashMap #ConcurrentHashMap #BackendDevelopment #SoftwareEngineering #DSA #FAANG #Multithreading #JavaCollections
To view or add a comment, sign in
-
🚀 Day 5 – What Really Happens Inside a HashMap? We use "HashMap" almost everywhere, but its internal working is quite interesting. Map<String, Integer> map = new HashMap<>(); map.put("key", 1); What happens internally? 👉 Step 1: "hashCode()" is calculated for the key 👉 Step 2: Hash is converted into an index (bucket location) 👉 Step 3: Value is stored in that bucket 💡 But what if two keys land in the same bucket? ✔ This is called a collision ✔ Java handles it using a Linked List (and converts to a Tree if it grows large) ⚠️ Important: - Retrieval ("get") again uses "hashCode()" + ".equals()" - So both must be properly implemented for custom objects 💡 Real takeaway: Good hashing = better performance Poor hashing = more collisions = slower operations This is why "HashMap" is fast on average (O(1)), but can degrade if not used properly. #Java #BackendDevelopment #HashMap #JavaInternals #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 42 - equals() & hashCode() & == You use HashMap. You use HashSet. You override equals() sometimes… But here’s what actually confuses most developers 👇 🔸 Why does this fail? map.get(new Employee(1, "Surya")); 🔸 Why does HashSet still allow duplicates even after overriding equals()? 🔸 Why does TreeSet remove elements even when equals() returns false? 🔸 Why does changing a field break HashMap retrieval? This is exactly where most developers struggle — not with syntax, but with how Java actually compares and stores objects internally. 📘 What I Covered Today (Deep Dive) 🔹Object comparison fundamentals • == vs equals() (reference vs logical equality) • When and why to override equals() 🔹 hashCode() complete understanding • Why hashing exists • How it improves performance • equals() & hashCode() contract 🔹Collections Internal Working (Core Backend Concept) • HashMap → bucket + equals() matching • HashSet → duplicate removal logic • TreeSet → compareTo() based equality • TreeMap → sorted key storage Real Use Cases with Custom Objects • Retrieval failures in HashMap • Duplicate issues in HashSet • Collision scenarios • Mutable key problems 💡 Most Asked Interview Question “Why do we need both equals() and hashCode()?” hashCode() → decides where to look equals() → decides what to match 📄 I’ve put everything into a clean, structured revision document with: • Step-by-step explanations • Real code scenarios • Collection internals • Interview-ready understanding If you're preparing for Java / Backend / Spring Boot roles (0–3 YOE): 📌 Save this — this is one of the most asked topics 🔁 Repost — helps others struggling with collections Follow Surya Mahesh Kolisetty and continue the journey with #100DaysOfBackend #Java #Collections #HashMap #HashSet #TreeSet #TreeMap #BackendDevelopment #InterviewPrep #SoftwareEngineering #Developers #Programming #LearningInPublic #CleanCode #CFBR #MicroServices #Design #JavaPrep #BackendDeveloper
To view or add a comment, sign in
-
Things About HashMap Most Developers Never Learn Properly 🤔 Most people think HashMap is just key-value storage. But your HashMap silently switches data structures. 🔁 In this post, you'll learn (You don't want to skip the slides 11 & 12 👀): • What bucket array really is • What Node actually stores • How collisions are handled • When LinkedList becomes a Tree • Why is the threshold 8 and 6 • When resizing happens instead of treeify • How equals() really works • Real HashMap internal flow Once you understand this, you'll never answer HashMap interview questions the same way again. Follow for more deep dive Java internals. #Java #HashMap #JavaDeveloper #SpringBoot #Backend #DSA #InterviewPrep #SoftwareEngineer #CodingInterview #JavaInternals
To view or add a comment, sign in
-
Day 95 of #365DaysOfLeetCode Challenge Today’s problem: **Path Sum III (LeetCode 437)** This one looks like a typical tree problem… but the optimal solution introduces a powerful concept: **Prefix Sum + HashMap in Trees** 💡 **Core Idea:** Instead of checking every possible path (which would be slow), we track **running sums** as we traverse the tree. 👉 If at any point: `currentSum - targetSum` exists in our map → we’ve found a valid path! 📌 **Approach:** * Use DFS to traverse the tree * Maintain a running `currSum` * Store prefix sums in a HashMap * Check how many times `(currSum - targetSum)` has appeared * Backtrack to maintain correct state ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Prefix Sum isn’t just for arrays — it can be **beautifully extended to trees**. This problem completely changed how I look at tree path problems: 👉 From brute-force traversal → to optimized prefix tracking 💭 **Key takeaway:** When a problem involves “subarray/paths with a given sum,” think: ➡️ Prefix Sum + HashMap #LeetCode #DSA #BinaryTree #PrefixSum #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
**Day 113 of #365DaysOfLeetCode Challenge** Today’s problem: **Contiguous Array (LeetCode 525)** We need to find the **longest contiguous subarray** with an equal number of `0`s and `1`s. At first glance, it feels like a sliding window problem… but the real solution is: 👉 **Prefix Sum + HashMap** 💡 **Core Idea:** Convert: * `0 → -1` * `1 → +1` Now the problem becomes: 👉 Find the longest subarray whose sum = `0` Because equal number of `0`s and `1`s cancel each other out. 📌 **Approach:** 1️⃣ Maintain running sum 2️⃣ Store first occurrence of each sum in HashMap 3️⃣ If same sum appears again: * Subarray between those indices has sum `0` 4️⃣ Maximize length 💡 Why store first occurrence only? Because earliest index gives the **longest possible subarray** ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Many binary array problems can be transformed into prefix sum problems by clever value mapping. 💭 **Key Takeaway:** When asked: * Equal 0s and 1s * Balanced values * Longest valid subarray Think: 👉 Prefix Sum 👉 HashMap 👉 First occurrence trick #LeetCode #DSA #PrefixSum #HashMap #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 17 – equals() and hashCode(): A Crucial Contract Today I explored why "equals()" and "hashCode()" are so important—especially when using collections like "HashMap" or "HashSet". --- 👉 By default: - "equals()" → compares object references - "hashCode()" → generates a hash based on memory location But in real applications, we override them. --- 💡 The contract I learned: ✔ If two objects are equal using "equals()", they must have the same "hashCode()" --- ⚠️ What happens if we break this? - "HashMap" may fail to retrieve values - Duplicate entries may appear in "HashSet" - Leads to very tricky bugs --- 👉 Example scenario: Two objects look identical (same data), but: - "equals()" returns true - "hashCode()" is different 👉 Result: Collections treat them as different objects 😬 --- 💡 Real takeaway: Whenever overriding "equals()", always override "hashCode()" properly. This is not just theory—it directly impacts how collections behave internally. #Java #BackendDevelopment #HashMap #JavaInternals #LearningInPublic
To view or add a comment, sign in
-
Solved a LeetCode hard in O(n). Couldn't use it in production. Last week I optimized an API endpoint that was timing out under load. The problem: filtering 50,000 order records to find duplicates based on multiple fields (customer_id, amount, timestamp within 5 min window). My first instinct? HashMap for O(n) lookup. Classic LeetCode muscle memory. Wrote it, tested locally flew through 100K records in 200ms. Pushed to staging. Staging worked. Production didn't. Here's what LeetCode doesn't teach you: garbage collection pauses are real. That HashMap was getting rebuilt on every request. With 50 requests/second, the young generation GC was running constantly. P99 latency spiked to 3 seconds because of GC pauses, even though P50 stayed at 200ms. Sure, I could've increased heap size. But that just delays full GC, making it worse when it finally hits. The fix: moved duplicate detection to PostgreSQL using a composite index and window function. Slightly slower average (350ms), but consistent. No GC spikes, predictable P99. LeetCode optimizes for algorithmic efficiency. Production optimizes for predictable latency under sustained load. What's an optimization that looked perfect on paper but failed under real traffic? #Java #Database #SystemDesign #LeetCode
To view or add a comment, sign in
-
🚀 Day 6 – HashMap vs ConcurrentHashMap (When Thread Safety Matters) Today I explored the difference between "HashMap" and "ConcurrentHashMap". We often use "HashMap" like this: Map<String, Integer> map = new HashMap<>(); 👉 But here’s the catch: "HashMap" is not thread-safe In a multi-threaded environment: - Multiple threads modifying it can lead to data inconsistency - Even cause infinite loops during resizing (rare but critical) So what’s the alternative? Map<String, Integer> map = new ConcurrentHashMap<>(); 👉 "ConcurrentHashMap" is designed for safe concurrent access 💡 Key difference I learned: ✔ "HashMap" - No synchronization - Faster in single-threaded scenarios ✔ "ConcurrentHashMap" - Uses segment-level locking / fine-grained locking - Allows multiple threads to read/write safely ⚠️ Insight: Instead of locking the whole map, it locks only a part of it → better performance than traditional synchronization. 💡 Real-world use: Whenever multiple threads are accessing shared data (like caching, session data), "ConcurrentHashMap" is a safer choice. #Java #BackendDevelopment #Concurrency #JavaInternals #LearningInPublic
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