<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ashutosh Kumar Tiwari on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Kumar Tiwari on Medium]]></description>
        <link>https://medium.com/@ashutosh-ceg?source=rss-954d2924e004------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yzu4plaSAs_Tph1hYAKE7w.png</url>
            <title>Stories by Ashutosh Kumar Tiwari on Medium</title>
            <link>https://medium.com/@ashutosh-ceg?source=rss-954d2924e004------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:04:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutosh-ceg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Day 32: Why List<?> Is Different from List<Object> in Java (A Common Interview Trap)]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-32-why-list-is-different-from-list-object-in-java-a-common-interview-trap-eb581954c47e?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb581954c47e</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 16:23:15 GMT</pubDate>
            <atom:updated>2026-07-05T16:23:15.621Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the biggest misconceptions among Java developers is thinking that these two declarations are equivalent:</p><pre>List&lt;Object&gt; objectList;<br>List&lt;?&gt; wildcardList;</pre><p>At first glance, they seem to represent “a list of objects.”</p><p>But they are <strong>fundamentally different</strong>.</p><p>In fact, understanding this difference is essential if you want to master Java Generics, write reusable APIs, or confidently answer interview questions.</p><p>Let’s explore why.</p><h3>The Misconception</h3><p>Many developers think:</p><p><em>Since every class in Java extends </em><em>Object, </em><em>List&lt;String&gt; should also be a </em><em>List&lt;Object&gt;.</em></p><p>Sounds reasonable…</p><p>Unfortunately, Java says <strong>No</strong>.</p><p>Consider this code:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>List&lt;Object&gt; objects = names;</pre><p>The compiler immediately throws an error.</p><p>Why?</p><h3>Java Generics Are Invariant</h3><p>The answer lies in one word:</p><p><strong>Invariance.</strong></p><p>In Java,</p><pre>String extends Object</pre><p>But</p><pre>List&lt;String&gt; ❌ does NOT extend List&lt;Object&gt;</pre><p>This is an intentional design decision to preserve type safety.</p><p>Imagine if Java allowed this:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>List&lt;Object&gt; objects = names;</pre><pre>objects.add(100);</pre><p>Now the original List&lt;String&gt; would contain an Integer.</p><p>Later,</p><pre>String s = names.get(0);</pre><p>What should happen?</p><p>The JVM would eventually fail with a ClassCastException.</p><p>Instead of allowing unsafe code, Java rejects it during compilation.</p><h3>Understanding List&lt;Object&gt;</h3><p>When you declare:</p><pre>List&lt;Object&gt; list = new ArrayList&lt;&gt;();</pre><p>you are explicitly saying:</p><p><em>“This list stores Objects.”</em></p><p>Since every class inherits from Object, you can add different types.</p><pre>list.add(&quot;Java&quot;);<br>list.add(100);<br>list.add(true);<br>list.add(3.14);</pre><p>Everything works because each value is an Object.</p><p>Reading values is also straightforward:</p><pre>Object obj = list.get(0);</pre><p>The compiler knows exactly what the list contains.</p><h3>Understanding List&lt;?&gt;</h3><p>Now consider:</p><pre>List&lt;?&gt; list;</pre><p>This means something completely different.</p><p>It means:</p><p><em>“This is a list of </em><strong><em>some unknown type</em></strong><em>.”</em></p><p>Notice the keyword:</p><p><strong>Unknown</strong></p><p>Java intentionally hides the actual type.</p><p>The list could be:</p><pre>List&lt;String&gt;</pre><p>or</p><pre>List&lt;Integer&gt;</pre><p>or</p><pre>List&lt;Employee&gt;</pre><p>The compiler simply doesn’t know.</p><h3>Why Can’t We Add Elements?</h3><p>Suppose we have:</p><pre>List&lt;?&gt; list = new ArrayList&lt;String&gt;();</pre><p>Now try:</p><pre>list.add(&quot;Java&quot;);</pre><p>Compilation error.</p><p>Why?</p><p>Because what if the actual list were:</p><pre>List&lt;Integer&gt;</pre><p>Adding a String would violate type safety.</p><p>Since Java cannot determine the actual generic type, it refuses every insertion (except null).</p><p>This is one of the most important rules of generics.</p><h3>Reading Is Perfectly Safe</h3><p>Although writing is restricted, reading is completely safe.</p><pre>Object obj = list.get(0);</pre><p>Every Java object inherits from Object.</p><p>Therefore, Java guarantees that every element can safely be returned as an Object.</p><h3>A Practical Example</h3><p>Suppose you’re writing a utility method that simply prints every element.</p><pre>public static void printList(List&lt;?&gt; list) {</pre><pre>    for (Object obj : list) {<br>        System.out.println(obj);<br>    }</pre><pre>}</pre><p>Now you can call it with:</p><pre>List&lt;String&gt;</pre><pre>List&lt;Integer&gt;</pre><pre>List&lt;Double&gt;</pre><pre>List&lt;Employee&gt;</pre><p>without creating overloaded methods.</p><p>This is one of the biggest advantages of wildcard generics.</p><h3>Why Frameworks Use List&lt;?&gt;</h3><p>If you’ve explored libraries like Spring, Hibernate, or Jackson, you’ve probably seen methods like:</p><pre>process(List&lt;?&gt; data)</pre><p>instead of</p><pre>process(List&lt;Object&gt; data)</pre><p>Why?</p><p>Because framework authors don’t care about the actual element type.</p><p>They only need to:</p><ul><li>iterate</li><li>inspect</li><li>serialize</li><li>validate</li></ul><p>Using List&lt;?&gt; makes the API flexible while preserving compile-time type safety.</p><h3>Interview Question</h3><p><strong>Question:</strong></p><p>Why can’t we assign a List&lt;String&gt; to a List&lt;Object&gt;?</p><p>A concise answer:</p><p><em>Because Java generics are invariant. If </em><em>List&lt;String&gt; were allowed to become </em><em>List&lt;Object&gt;, someone could insert a non-String object, breaking type safety.</em></p><h3>Quick Trick to Remember</h3><p>Whenever you see:</p><pre>List&lt;Object&gt;</pre><p>Think:</p><p><strong><em>“I own this list. I can put Objects into it.”</em></strong></p><p>Whenever you see:</p><pre>List&lt;?&gt;</pre><p>Think:</p><p><strong><em>“I don’t know what’s inside. I can safely read, but I shouldn’t write.”</em></strong></p><p>That single idea explains most wildcard-related questions.</p><h3>Final Thoughts</h3><p>List&lt;Object&gt; and List&lt;?&gt; may look similar, but they represent two completely different concepts.</p><ul><li>List&lt;Object&gt; is about <strong>storing Objects</strong>.</li><li>List&lt;?&gt; is about <strong>working safely with collections of unknown types</strong>.</li></ul><p>Understanding this distinction will not only help you write better generic code but also make many advanced Java APIs much easier to understand.</p><p>As your Java journey progresses, you’ll notice that <strong>wildcards (</strong><strong>?, </strong><strong>? extends, and </strong><strong>? super) appear everywhere</strong>—from the Collections Framework to Streams and popular frameworks like Spring.</p><p>Mastering them is one of the key steps toward becoming a confident Java developer.</p><h3>📚 This article is part of my 100 Days of Java series, where I explain one important Java concept every day with practical examples, interview insights, and internal working.</h3><p>If you found this article useful, I’d love to hear your thoughts. Connect with me on LinkedIn and follow the series as we continue exploring Java from the basics to advanced internals.</p><p><strong>Happy Coding! ☕🚀</strong></p><p><strong>#Java #100DaysOfJava #Generics #Collections #BackendDevelopment #SoftwareEngineering #JavaInterview #Programming #LearningInPublic</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb581954c47e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[India’s AI Moment: What the AI Impact Summit Taught Us.  AI Impact Summit 2026]]></title>
            <link>https://medium.com/@ashutosh-ceg/indias-ai-moment-what-the-ai-impact-summit-taught-us-ai-impact-summit-2026-b06ddaf126ed?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/b06ddaf126ed</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 14:42:11 GMT</pubDate>
            <atom:updated>2026-02-25T14:42:11.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, the <strong>AI Impact Summit</strong> took place in New Delhi, bringing together policymakers, technologists, researchers, and industry leaders to discuss how Artificial Intelligence can shape our future.</p><p>Unfortunately, I couldn’t attend the summit in person. But after following the conversations, reports, and shared insights, I realized something important:</p><p>You don’t need to be in the room to understand that something big is happening.</p><p>This summit wasn’t just about powerful algorithms or futuristic tools. It was about how AI can make real differences in real lives—especially in a country like India.</p><h3>Why This Summit Matters</h3><p>India is at a unique point in time.<br>We have:</p><ul><li>A massive population</li><li>Growing digital infrastructure</li><li>A young tech workforce</li><li>And some of the world’s biggest real-world challenges</li></ul><p>When AI is applied here, its impact isn’t small—it&#39;s multiplied.</p><p>From healthcare to farming, from education to public services, AI can help solve problems at scale. That’s what made this summit important: the shift from <em>“what AI can do”</em> to <em>“who AI should help.”</em></p><h3>Here is the 10 Key Outcomes from the Summit (in simple terms):</h3><h3>1. India is becoming a serious player in AI</h3><p>The world is no longer seeing India only as an IT services hub. It’s starting to recognize India as a place where meaningful AI solutions can be built and deployed.</p><h3>2. AI must help people, not just businesses</h3><p>There was strong emphasis on building AI for social good—tools that help doctors, teachers, farmers, and small business owners.</p><h3>3. Jobs will change, not vanish</h3><p>Instead of replacing humans, AI is expected to take over repetitive tasks and allow people to focus on creative and problem-solving work.</p><h3>4. Ethics and responsibility are now core topics</h3><p>Privacy, fairness, and transparency are no longer “nice-to-have” features. They are becoming part of the foundation of AI systems.</p><h3>5. Healthcare can improve dramatically</h3><p>AI can help in early disease detection, faster diagnosis, and better resource planning—especially in underserved areas.</p><h3>6. Education can become more personal</h3><p>AI-based learning platforms can adapt to each student’s pace and style of learning, making education more inclusive.</p><h3>7. Rural India can benefit directly</h3><p>From predicting crop diseases to giving weather-based farming advice, AI can empower farmers with better decisions.</p><h3>8. Smarter public services are possible</h3><p>Traffic systems, disaster response, and city planning can become more efficient with data-driven insights.</p><h3>9. Innovation and startups will grow</h3><p>Events like this encourage collaboration between government bodies, startups, universities, and large enterprises.</p><h3>10. India’s AI future looks practical</h3><p>The focus is shifting from theory and research-only models to solutions that can be used today in everyday life.</p><h3>What This Means for Us as Engineers</h3><p>As a software engineer, this summit reminded me that :</p><p><em>Technology is not just about writing code—it&#39;s about writing code that matters.</em></p><p>AI gives us power. But with that power comes responsibility:</p><ul><li>To protect user data</li><li>To avoid bias</li><li>To build tools that serve people, not control them</li></ul><p>India has the talent and scale to lead the world in <strong>responsible AI</strong>, not just fast AI.</p><h3>Final Thoughts</h3><p>Even though I couldn’t attend the summit, its message reached me loud and clear:</p><p><strong>AI is not the future—it is the present.</strong><br>And India has a real chance to shape how it is used for good.</p><p>The question is no longer:</p><p><em>“Can we build this with AI?”</em></p><p>The better question is:</p><p><em>“Should we build this—and who does it help?”</em></p><p>If we keep people at the center of technology, the impact of AI can be not just big—but meaningful.</p><h3>If you liked this, you might agree with this too:</h3><p>AI should not replace humans.<br>AI should <strong>support</strong> humans.</p><p>AI isn’t just the future—it&#39;s happening now. And India has the potential to lead in responsible, impactful AI for people everywhere.</p><p>As a technologist, this motivates me to build systems that are not only smart but also meaningful and responsible.</p><p>Let’s build technology that lifts people up—not just impresses with complexity.</p><p>Looking forward to seeing how our country shapes the next chapter of AI. 🇮🇳</p><p>Let’s build that future.</p><p>#Artificial Intelligence #India #ResponsibleAI #Innovation #Technology #BhararInAI #TechForGood #FutureOfWork #AIForEveryone #BharatInTech #TechInBharat #AIImpactSummit #Bharat #AI #IndiaAIImpactSummit2026</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b06ddaf126ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covariance and Contravariance in Java Generics—Explained Without Confusion]]></title>
            <link>https://medium.com/@ashutosh-ceg/covariance-and-contravariance-in-java-generics-explained-without-confusion-ae1d34c6e81f?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae1d34c6e81f</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 16:16:49 GMT</pubDate>
            <atom:updated>2026-01-14T16:16:49.230Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with Java Generics long enough, you’ve definitely encountered this syntax:</p><pre>? extends T<br>? super T</pre><p>And if you’re being honest, you probably memorized <em>when</em> to use them without fully understanding <em>why</em> they exist.</p><p>This article aims to fix that.</p><p>We’ll focus on <strong>intuition first</strong>, then code, and finally interview-level clarity.</p><h3>The Root Problem: Invariance in Java Generics</h3><p>In Java, generics are <strong>invariant</strong> by default.</p><p>That means this does <strong>not</strong> compile:</p><pre>List&lt;Integer&gt; ints = new ArrayList&lt;&gt;();<br>List&lt;Number&gt; nums = ints; // Compilation error</pre><p>Even though Integer <em>is a</em> Number,<br> List&lt;Integer&gt; is <strong>not</strong> a subtype of List&lt;Number&gt;.</p><p>Why?</p><p>Because allowing this would break type safety.</p><p>Imagine:</p><pre>nums.add(3.14); // Double added<br>Integer i = ints.get(0); // Runtime problem</pre><p>Java blocks this at compile time.</p><p>So how do we handle flexibility <em>safely</em>?</p><p>That’s where <strong>variance</strong> comes in.</p><h3>What Is Variance?</h3><p>Variance describes how <strong>subtyping relationships</strong> behave with generics.</p><p>Java supports:</p><ul><li><strong>Covariance</strong> → ? extends T</li><li><strong>Contravariance</strong> → ? super T</li></ul><p>Each solves a <em>different</em> problem.</p><h3>Covariance — ? extends T</h3><h3>What it means</h3><pre>List&lt;? extends Number&gt;</pre><p>This says:</p><p><em>“This list contains </em><strong><em>Number or its subclasses</em></strong><em>, but I don’t know exactly which.”</em></p><h3>What you can do</h3><p>You can <strong>read safely</strong>:</p><pre>List&lt;? extends Number&gt; list = new ArrayList&lt;Integer&gt;();<br>Number n = list.get(0); // safe</pre><p>But you <strong>cannot add</strong>:</p><pre>list.add(10);    // compile-time error<br>list.add(3.14); // still not allowed</pre><p>Why?</p><p>Because the compiler doesn’t know whether the list is:</p><ul><li>List&lt;Integer&gt;</li><li>List&lt;Double&gt;</li><li>List&lt;Long&gt;</li></ul><p>Allowing insertion would break type safety.</p><h3>Mental model</h3><p><strong>Covariance = read-only (mostly)</strong></p><p>It’s ideal when your code <strong>produces data</strong>.</p><h3>Contravariance — ? super T</h3><h3>What it means</h3><pre>List&lt;? super Integer&gt;</pre><p>This says:</p><p><em>“This list can hold </em><em>Integer or any of its parent types.”</em></p><h3>What you can do</h3><p>You can <strong>add safely</strong>:</p><pre>List&lt;? super Integer&gt; list = new ArrayList&lt;Number&gt;();<br>list.add(10); // allowed</pre><p>But when reading:</p><pre>Object o = list.get(0); // Only Object is guaranteed</pre><p>Why only Object?</p><p>Because the actual list could be:</p><ul><li>List&lt;Integer&gt;</li><li>List&lt;Number&gt;</li><li>List&lt;Object&gt;</li></ul><p>The compiler plays it safe.</p><h3>Mental model</h3><p><strong>Contravariance = write-friendly</strong></p><p>It’s ideal when your code <strong>consumes data</strong>.</p><h3>The Golden Rule: PECS</h3><p>This single rule explains almost everything:</p><p><strong><em>P</em></strong><em>roducer → </em><em>extends</em></p><p><strong><em>C</em></strong><em>onsumer → </em><em>super</em></p><p>If your method:</p><ul><li><strong>Produces</strong> data → use ? extends</li><li><strong>Consumes</strong> data → use ? super</li></ul><h3>Example</h3><pre>void printNumbers(List&lt;? extends Number&gt; list) { ... } // producer<br>void addNumbers(List&lt;? super Integer&gt; list) { ... }    // consumer</pre><h3>Why Java Didn’t Choose Simpler Generics</h3><p>Languages like Kotlin use declaration-site variance (out, in).</p><p>Java chose <strong>use-site variance</strong> (? extends, ? super) to:</p><ul><li>Maintain backward compatibility</li><li>Avoid breaking existing code</li><li>Give fine-grained control at method level</li></ul><p>It’s verbose — but very explicit.</p><h3>Common Interview Mistakes</h3><p>“extends allows adding child objects”<br>“super is rarely useful”<br>“Covariance and inheritance are the same”</p><p>All incorrect.</p><p>Variance is about <strong>what operations are type-safe</strong>, not just hierarchy.</p><h3>One-Line Interview Answer</h3><p>If you need a crisp response:</p><p><em>Covariance (</em><em>? extends) allows safe reading from generic structures, while contravariance (</em><em>? super) allows safe writing, both preserving type safety in Java generics.</em></p><h3>Final Thoughts</h3><p>Once you stop thinking of extends and super as inheritance keywords—and start thinking in terms of <strong>read vs write safety</strong>—generics become far less intimidating.</p><p>This concept shows up everywhere:</p><ul><li>Collections</li><li>Streams</li><li>Functional interfaces</li><li>Framework APIs</li></ul><p>Mastering it puts you firmly in <strong>senior Java developer territory</strong>.</p><p>If this article helped clarify generics, feel free to clap 👏 or share.<br>I’m writing a <strong>Day-by-Day Java Concept Series</strong>, focusing on internals and interview depth.</p><p>Happy coding ☕</p><p><strong>#100DaysOfJava #JavaInterview #Collections #AshutoshTiwari </strong><em>#Java #Programming #CleanCode #MediumBlog</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae1d34c6e81f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparable vs Comparator in Java: The Sorting Question That Never Goes Away]]></title>
            <link>https://medium.com/@ashutosh-ceg/comparable-vs-comparator-in-java-the-sorting-question-that-never-goes-away-6f9da57f90be?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f9da57f90be</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 16:18:02 GMT</pubDate>
            <atom:updated>2026-01-08T16:18:02.234Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever prepared for Java interviews — or written real-world Java code — you’ve definitely faced this question:</p><p><strong>“What’s the difference between Comparable and Comparator?”</strong></p><p>At first glance, both seem to solve the same problem: <strong>sorting objects</strong>.<br> But once you dig deeper, you realize they solve <em>different design problems</em>.</p><p>Let’s break it down in a practical, developer-first way.</p><h3>Why Java Needs Comparable and Comparator</h3><p>Java collections like Collections.sort() and Arrays.sort() need to know <strong>how objects should be ordered</strong>.</p><p>For primitive types, this is obvious.<br> For custom objects (like Employee, Order, Product), Java needs guidance.</p><p>That guidance comes in <strong>two flavors</strong>:</p><ul><li>Natural ordering → Comparable</li><li>Custom or multiple orderings → Comparator</li></ul><h3>Comparable: Defining Natural Order</h3><p>Comparable is used when a class has <strong>one clear, natural way</strong> to be sorted.</p><h3>Key idea:</h3><p>The object knows how to compare itself with another object.</p><h3>Example: Sorting Employees by Salary</h3><pre>class Employee implements Comparable&lt;Employee&gt; {<br>    int salary;<br><br><br>Employee(int salary) {<br>        this.salary = salary;<br>    }<br>    @Override<br>    public int compareTo(Employee other) {<br>        return this.salary - other.salary;<br>    }<br>}<br></pre><p>Now you can sort without any extra logic:</p><pre>Collections.sort(employeeList);</pre><h3>Characteristics of Comparable</h3><ul><li>Sorting logic lives <strong>inside the class</strong></li><li>Uses compareTo()</li><li>Only <strong>one</strong> sorting strategy</li><li>Modifies the class design</li></ul><p>This works well when:</p><ul><li>The sorting rule is obvious</li><li>The class is under your control</li></ul><h3>Comparator: External and Flexible Sorting</h3><p>What if the same object needs to be sorted in <strong>different ways</strong>?</p><p>Salary today.<br> Name tomorrow.<br> Joining date next week.</p><p>This is where Comparator shines.</p><h3>Key idea:</h3><p>Sorting logic lives outside the class.</p><h3>Example: Sorting Employees by Name</h3><pre>Comparator&lt;Employee&gt; byName =<br>        (e1, e2) -&gt; e1.name.compareTo(e2.name);</pre><p>Usage:</p><pre>Collections.sort(employeeList, byName);</pre><p>You can define as many comparators as you want:</p><pre>Comparator&lt;Employee&gt; bySalary =<br>        Comparator.comparingInt(e -&gt; e.salary);</pre><h3>Characteristics of Comparator</h3><ul><li>Uses compare()</li><li>No modification to the original class</li><li>Supports <strong>multiple sorting strategies</strong></li><li>Ideal for dynamic or runtime sorting</li></ul><h3>Comparable vs Comparator — Side by Side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*r1L7AX_jAwYOzD-wC9L4_w.png" /></figure><p>Common Interview Traps (Be Careful!)</p><h3>“Comparator is better than Comparable”</h3><p>Wrong.<br> They solve <strong>different design problems</strong>.</p><h3>“You can’t sort without Comparable”</h3><p>Wrong.<br> Comparator alone is enough.</p><h3>“Comparable supports multiple sorting orders”</h3><p>Wrong.<br> That’s exactly why Comparator exists.</p><h3>A Solid Interview Answer</h3><p>If you want a crisp interview-ready explanation:</p><p>A</p><p><strong><em>Comparable defines the natural ordering of objects by implementing </em></strong><strong><em>compareTo() inside the class, whereas Comparator provides external and customizable sorting logic using </em></strong><strong><em>compare() without modifying the class.</em></strong></p><p>Short. Clear. Correct.</p><h3>When Should You Use Which?</h3><p>Use <strong>Comparable</strong> when:</p><ul><li>There is one obvious natural order</li><li>You own the class design</li></ul><p>Use <strong>Comparator</strong> when:</p><ul><li>You need multiple sorting strategies</li><li>Sorting rules change frequently</li><li>You don’t want to modify the domain class</li></ul><h3>Final Thoughts</h3><p>In real projects, <strong>Comparator + lambdas</strong> dominate modern Java codebases.<br> But understanding <strong>Comparable</strong> is essential — especially for interviews and clean domain modeling.</p><p>Master both, and sorting questions stop being tricky.</p><p>If you found this helpful, feel free to share or clap 👏<br> I’m building a <strong>Day-by-Day Java Concept Series</strong> — more deep dives coming soon.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f9da57f90be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 29: IdentityHashMap in Java — When == Matters More Than .equals()]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-29-identityhashmap-in-java-when-matters-more-than-equals-cd306298f797?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd306298f797</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 15:39:04 GMT</pubDate>
            <atom:updated>2026-01-04T15:39:04.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 29: IdentityHashMap in Java — When == Matters More Than .equals()</h3><p>In Java, we are trained to believe one rule:</p><p><strong><em>Keys in a Map are compared using </em></strong><strong><em>.equals()</em></strong></p><p>That rule is true — <strong>except for one special Map</strong>:<br> <strong>IdentityHashMap</strong></p><p>This class breaks the norm in a very intentional way.<br> Let’s understand <em>why it exists</em>, <em>how it works</em>, and <em>when you should (and shouldn’t) use it</em>.</p><h3>What Is IdentityHashMap?</h3><p>IdentityHashMap is a Map implementation where:</p><ul><li>Keys are compared using <strong>reference equality (</strong><strong>==)</strong></li><li>NOT logical equality (.equals())</li></ul><p>In other words:</p><p><em>Two keys are equal </em><strong><em>only if they are the same object in memory</em></strong><em>.</em></p><h3>A Simple Example (The Surprise)</h3><pre>Map&lt;String, String&gt; map = new IdentityHashMap&lt;&gt;();</pre><pre>String a = new String(&quot;Java&quot;);<br>String b = new String(&quot;Java&quot;);</pre><pre>map.put(a, &quot;First&quot;);<br>map.put(b, &quot;Second&quot;);</pre><pre>System.out.println(map.size()); // Output: 2</pre><p>Why?</p><p>Because:</p><pre>a.equals(b) → true<br>a == b      → false</pre><p>And IdentityHashMap only cares about ==.</p><h3>How Does It Work Internally?</h3><p>Internally, IdentityHashMap:</p><ul><li>Uses System.identityHashCode() instead of hashCode()</li><li>Stores keys in an array-based structure</li><li>Compares keys using ==</li></ul><p>This ensures:<br> ✔ Fast lookups<br> ✔ No dependency on equals() / hashCode() implementations</p><h3>IdentityHashMap vs HashMap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*oaBspDXtGwZWipcHdwA5iQ.png" /></figure><h3>Why Does IdentityHashMap Exist?</h3><p>You might ask:</p><p><em>“Why would anyone want this behavior?</em></p><p>Here are real-world reasons:</p><p>Object graph traversal<br>Serialization frameworks<br>Dependency injection containers<br>Cycle detection<br>Maintaining object identity<br>Debugging tools</p><p>In such cases, two objects with the same content are <strong>not the same object</strong>.</p><h3>Important Points</h3><p>Do NOT use IdentityHashMap as a general-purpose map</p><p>Very confusing if used accidentally</p><p>Not intuitive for business logic</p><p>This map is a <strong>specialized tool</strong>, not a replacement for HashMap.</p><h3>Interview-Ready Explanation</h3><p>If asked:</p><p><em>“What is IdentityHashMap?”</em></p><p>A strong answer:</p><p><em>IdentityHashMap compares keys using reference equality (</em><em>==) instead of </em><em>.equals(). It uses </em><em>System.identityHashCode() internally and is useful when object identity matters more than logical equality, such as in serialization or graph traversal.</em></p><h3>Final Thoughts</h3><p>IdentityHashMap teaches an important lesson:</p><p><strong><em>Not all Maps are about value equality — sometimes identity matters.</em></strong></p><p>Knowing this class tells interviewers you understand Java beyond the surface.</p><p>This was <strong>Day 29</strong> of my <em>100 Days of Java Core Concepts</em> series.<br> More coming soon.</p><p><strong>#100DaysOfJava #JavaInterview #Collections #AshutoshTiwari </strong><em>#Java #Programming #CleanCode #MediumBlog</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd306298f797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 28: WeakHashMap in Java—How It Works with Garbage Collection (GC)]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-28-weakhashmap-in-java-how-it-works-with-garbage-collection-gc-880c1d4851af?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/880c1d4851af</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 17:47:38 GMT</pubDate>
            <atom:updated>2025-12-24T17:47:38.213Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory leaks are one of the hardest problems to detect in Java applications. Sometimes the issue isn’t complex logic—it’s simply <strong>using the wrong Map implementation</strong>.</p><p>One such underrated but powerful class is WeakHashMap.</p><p>Let’s understand <strong>what it is</strong>, <strong>how it works</strong>, and <strong>when you should use it</strong>.</p><h3>What Is WeakHashMap?</h3><p>WeakHashMap is a special type of Map where <strong>keys are stored as weak references</strong>.</p><p>This means:</p><p><em>If a key is no longer strongly referenced anywhere in your application, the garbage collector</em><strong><em> is free to remove that entry</em></strong><em> from the map.</em></p><p>This behavior makes it WeakHashMap ideal for memory-sensitive use cases.</p><h3>A Quick Refresher: Java References</h3><p>Java has different types of references:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*fKSb5RpppPLqxDXPJhrYVg.png" /></figure><p>HashMap uses <strong>strong references</strong>.<br> WeakHashMap uses <strong>weak references for keys</strong>.</p><h3>HashMap vs WeakHashMap (Conceptually)</h3><h3>HashMap:</h3><pre>Map&lt;Object, String&gt; map = new HashMap&lt;&gt;();</pre><p>Even if the key object is no longer used elsewhere, the map <strong>keeps it alive</strong>.</p><p>Result:<br> ❌ Potential memory leak</p><h3>WeakHashMap:</h3><pre>Map&lt;Object, String&gt; map = new WeakHashMap&lt;&gt;();</pre><p>If the key is no longer referenced anywhere else, GC <strong>automatically removes the entry</strong>.</p><p>Result:<br> ✅ Memory-friendly</p><h3>Simple Example (GC in Action)</h3><pre>Map&lt;Object, String&gt; map = new WeakHashMap&lt;&gt;();</pre><pre>Object key = new Object();<br>map.put(key, &quot;Important Data&quot;);</pre><pre>key = null;   // Remove strong reference<br>System.gc();</pre><pre>System.out.println(map.size()); // Likely 0</pre><p>Once the key becomes unreachable, GC can clear the entry.</p><p>Note: Garbage collection is <strong>not guaranteed to run immediately</strong>, so results may vary.</p><h3>Internal Working (Simplified)</h3><p>Internally:</p><ul><li>Keys are wrapped in WeakReference</li><li>Values are stored normally</li><li>When GC clears a weak reference, the map removes the entry</li></ul><p>Think of WeakHashMap as a map that says:</p><p><em>“I’ll keep your data </em><strong><em>only if you still care about the key</em></strong><em>.”</em></p><h3>Important Points to Remember</h3><p>✔ Only <strong>keys</strong> are weak, not values<br> ✔ GC behavior is <strong>non-deterministic</strong><br> ✔ You should NOT depend on it for exact cleanup timing<br> ✔ Not suitable for business-critical data storage</p><h3>When Should You Use WeakHashMap?</h3><p>WeakHashMap is ideal for:</p><ul><li>Caching data</li><li>Storing metadata</li><li>Listener registrations</li><li>Temporary mappings</li><li>Avoiding memory leaks in frameworks</li></ul><p>Frameworks like Hibernate and Spring use weak references internally for similar reasons.</p><h3>When NOT to Use WeakHashMap</h3><p>Avoid it when:</p><ul><li>You need guaranteed persistence of entries</li><li>Data is critical and must not disappear</li><li>You need predictable behavior</li></ul><p>Remember: <strong>GC decides the lifecycle, not you.</strong></p><h3>Interview-Ready Explanation</h3><p>If an interviewer asks:</p><p><em>“Why would you use WeakHashMap?”</em></p><p>A strong answer:</p><p><em>“WeakHashMap stores keys using weak references, allowing entries to be garbage collected when keys are no longer strongly referenced. This helps prevent memory leaks, especially in cache or metadata use cases.”</em></p><p>That answer shows real-world understanding.</p><h3>Final Thoughts</h3><p>WeakHashMap is not commonly used — but when used correctly, it can solve serious memory problems.</p><p>It’s a great reminder that:</p><p><em>Choosing the right data structure is as important as writing correct logic.</em></p><p><strong>#100DaysOfJava #JavaInterview #Collections #AshutoshTiwari </strong><em>#Java #Programming #CleanCode #MediumBlog</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880c1d4851af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 27: How PriorityQueue Really Works in Java (And Why It’s Not What You Think)]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-27-how-priorityqueue-really-works-in-java-and-why-its-not-what-you-think-a9ecfa32a40b?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ecfa32a40b</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 18:22:18 GMT</pubDate>
            <atom:updated>2025-12-08T18:22:18.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Java developers assume this:</p><p><em>“PriorityQueue keeps elements in sorted order.”</em></p><p>That sounds right—but it’s technically <strong>wrong</strong>.</p><p>A PriorityQueue doesn’t maintain a fully sorted list.<br> Instead, it uses a <strong>heap data structure</strong> that only guarantees one thing:</p><p>The <strong>highest-priority element</strong> is always at the top.</p><p>Let’s break this down cleanly.</p><h3>What Is a PriorityQueue?</h3><p>In Java:</p><pre>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();</pre><p>By default, a PriorityQueue in Java is a <strong>min-heap</strong>:</p><ul><li>The <em>smallest element</em> has the highest priority.</li><li>The smallest element is always at the <strong>head</strong> of the queue.</li></ul><h3>The Real Engine: Binary Heap</h3><p>Internally, Java’s PriorityQueue is backed by a <strong>binary heap</strong>, which is a complete binary tree stored inside an <strong>array</strong>.</p><p>Visual view of how it looks:</p><pre>        10<br>       /  \<br>     30    20</pre><p>Heap rule:</p><p><em>Parent node ≤ Child nodes.</em></p><p>That’s it.<br> There’s no guarantee about the left or right subtree being sorted.</p><h3>A Popular Misconception</h3><p>Try this code:</p><pre>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();<br>pq.add(30);<br>pq.add(10);<br>pq.add(20);</pre><pre>System.out.println(pq);</pre><p>Expected by beginners:</p><pre>[10, 20, 30]</pre><p>Actual output:</p><pre>[10, 30, 20]</pre><p>It looks unsorted — because it <strong>is</strong>.<br> The only guarantee is that:</p><pre>pq.peek()</pre><p>will always return 10.</p><h3>How Elements Are Added</h3><p>When you insert elements:</p><ol><li>They are added at the end of the array</li><li>A process called <strong>heapify-up</strong> starts</li><li>Elements are swapped up the tree until the heap property is restored</li></ol><p>This takes <strong>O(log n)</strong> time.</p><h3>How to Get Sorted Output (Correct Way)</h3><p>If you want sorted order, you must remove elements one by one:</p><pre>while (!pq.isEmpty()) {<br>    System.out.println(pq.poll());<br>}</pre><p>Why poll() and not peek()?</p><p>Because:</p><ul><li>peek() only looks at the top</li><li>poll() removes and re-heapifies the structure.</li></ul><h3>Creating a Max Heap</h3><p>By default, Java gives you a <strong>min heap</strong>.</p><p>To make it a <strong>max heap</strong>:</p><pre>PriorityQueue&lt;Integer&gt; maxHeap =<br>    new PriorityQueue&lt;&gt;(Collections.reverseOrder());</pre><p>Now the largest element will be at the top.</p><h3>Real-World Use Cases</h3><p>PriorityQueue is commonly used for:</p><ul><li>Task scheduling</li><li>Job queues</li><li>CPU scheduling simulations</li><li>Dijkstra’s shortest path algorithm</li><li>A* pathfinding</li><li>Event-driven simulations</li></ul><p>Whenever “priority” matters more than “insertion order.”</p><h3>Interview-Ready Explanation</h3><p>If an interviewer asks:</p><p><em>“How does PriorityQueue maintain order internally?”</em></p><p>You can confidently say:</p><p><em>“Java’s PriorityQueue uses a binary heap internally. It does not fully sort elements. It only guarantees that the head of the queue is always the smallest or highest-priority element. Insertion and removal take O(log n) time because heapify operations are performed.”</em></p><p>This answer shows real depth.</p><h3>Final Thoughts</h3><p>PriorityQueue is one of those data structures that feels simple at the surface — but has beautifully optimized behavior under the hood.</p><p>If you understand heaps, you understand PriorityQueue.</p><p>This is <strong>Day 27</strong> of my <em>100 Days of Java Core Concepts</em> series. More coming soon.</p><p>Follow me for more such insights: <strong>#100DaysOfJava #JavaLearning #JavaInterview #AshutoshTiwari</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ecfa32a40b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 26: TreeMap vs HashMap — The Real Difference Beyond Just “Sorted vs Unsorted”]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-26-treemap-vs-hashmap-the-real-difference-beyond-just-sorted-vs-unsorted-c8c84c6bce2e?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c84c6bce2e</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 18:26:11 GMT</pubDate>
            <atom:updated>2025-12-04T18:26:11.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 26: TreeMap vs HashMap — The Real Difference Beyond Just “Sorted vs Unsorted”</h3><p>As Java developers, we often say:<br> <strong>“Use HashMap for speed, TreeMap for sorting.”</strong></p><p>But the internal differences go much deeper than that. In interviews, this topic shows up not because it’s difficult, but because <strong>most developers only know the surface-level answer.</strong></p><p>Let’s break down HashMap vs TreeMap the way senior engineers explain it.</p><h3>1. The Core Purpose</h3><h3>HashMap → Fast, Unordered Key–Value Storage</h3><p>Its goal is simple: <strong>speed</strong>.<br>You give it a key, it computes a hash, finds a bucket, and stores the entry.</p><h3>TreeMap → Sorted Key–Value Storage</h3><p>Its goal is <strong>ordering</strong>.<br>It keeps all keys in sorted order using a self-balancing Red-Black tree.</p><p>So even though both store key–value pairs, their motivations are different.</p><h3>2. Internal Data Structures</h3><p>This is where the difference really starts.</p><p>Map Type Internal Structure</p><p><strong>HashMap </strong>Array + LinkedList + (Tree nodes after Java 8)</p><p><strong>TreeMap </strong>Red-Black Tree</p><p>Let’s visualize both.</p><h3>HashMap Internal Structure (Simplified)</h3><pre>Index:   0     1         2      3<br>        ---------------------------------<br>Bucket: null  Node → Node  null   Node</pre><p>It’s based on hashing:</p><pre>index = (n - 1) &amp; hash(key)</pre><p>If a bucket has collisions, Java 8+ may convert the chain into a <strong>tree</strong> for faster lookup:</p><pre>     Bucket 3:<br>      (root)<br>      /    \<br>   Node    Node</pre><h3>TreeMap Internal Structure (Red-Black Tree)</h3><pre>        (50)<br>       /     \<br>    (20)     (70)<br>    /  \     /  \<br> (10) (40) (60) (90)</pre><p>Every time you insert or delete, the tree <strong>rebalances</strong> itself to maintain sorted order.</p><p>That’s why operations take <strong>O(log n)</strong> time.</p><h3>3. Performance Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*sndagdpJB1CcWJC4EYIvQg.png" /></figure><p>For large datasets, this difference becomes very noticeable.</p><p>👉 <strong>If you need pure speed → HashMap</strong><br> 👉 <strong>If you need sorted keys → TreeMap</strong></p><h3>4. Ordering Behavior</h3><p>This is where many interviews start.</p><h3>HashMap</h3><ul><li>No defined order</li><li>Keys appear random because hashing scatters them across the array</li></ul><h3>TreeMap</h3><ul><li>Keys are <strong>always sorted</strong></li><li>Natural order (e.g., alphabetical, numeric) or custom Comparator</li></ul><p>Example:</p><pre>Map&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();<br>map.put(50, &quot;A&quot;);<br>map.put(10, &quot;B&quot;);<br>map.put(30, &quot;C&quot;);<br>// Output: 10, 30, 50</pre><p>This makes TreeMap particularly useful for:</p><ul><li>Range queries</li><li>Prefix matching</li><li>Floor/ceiling lookups</li><li>Ordered reports</li></ul><h3>5. Null Key Handling</h3><p>A subtle but critical difference.</p><p>HashMap , Allows <strong>one null key</strong></p><p>TreeMap , Does <strong>not allow null key</strong></p><p>Why?</p><p>Because TreeMap must <strong>compare</strong> keys to maintain order.<br> Comparing null to another value throws NullPointerException.</p><h3>6. When Should You Use Which?</h3><h3>Use HashMap when:</h3><ul><li>You want O(1) lookup</li><li>Order does not matter</li><li>You’re building caches, counters, storage maps</li></ul><h3>Use TreeMap when:</h3><ul><li>You need sorted results</li><li>You want range views (subMap, headMap, tailMap)</li><li>You’re building tables, reports, leaderboard ranking, or time-series lookup</li></ul><h3>7. Interview-Ready Summary</h3><p>If an interviewer asks you:</p><p><em>“Between TreeMap and HashMap, which one will you choose?”</em></p><p>A perfect answer is:</p><p><strong><em>HashMap is faster because it uses hashing and provides O(1) average lookup.<br> TreeMap keeps keys sorted using a Red-Black tree and operations run in O(log n).<br> HashMap allows null keys, TreeMap doesn’t.<br> Use HashMap for speed, TreeMap when ordering matters.</em></strong></p><p>Short, sharp, and complete.</p><h3>Final Thoughts</h3><p>TreeMap and HashMap solve different problems.<br> Knowing when to use which is a hallmark of a strong Java engineer.</p><p>This is Day 26 of my <strong>100 Days of Java Core Concepts</strong> series.<br> More deep dives coming — stay tuned!</p><p>Follow me for more such insights: <strong>#100DaysOfJava #JavaLearning #JavaInterview #AshutoshTiwari</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c84c6bce2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 25: How HashMap Works Internally — Buckets, Collisions & Resizing (A Deep Dive for Java…]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-25-how-hashmap-works-internally-buckets-collisions-resizing-a-deep-dive-for-java-7905b8497eda?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/7905b8497eda</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 18:28:25 GMT</pubDate>
            <atom:updated>2025-11-25T18:28:25.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 25: How HashMap Works Internally — Buckets, Collisions &amp; Resizing (A Deep Dive for Java Developers)</h3><p>HashMap is everywhere — whether you’re caching API responses, storing user sessions, or performing quick lookups.<br> But interviewers <em>love</em> pushing developers beyond the basic:</p><p><em>“You use HashMap daily — but do you know how it works internally?”</em></p><p>Let’s decode the internals of HashMap in a clean, visual, and interview-ready way.</p><h3>1. The Core Idea Behind HashMap</h3><p>A HashMap stores data in the form of <strong>key-value pairs</strong>.<br> But beneath the surface, it’s basically a combination of:</p><ul><li><strong>An array of buckets</strong></li><li><strong>Linked lists or balanced trees</strong> (after Java 8)</li></ul><p>Each bucket represents a position where entries will be stored.</p><h3>2. What Exactly Is a Bucket?</h3><p>Buckets are just <strong>indexes of an internal array</strong>, where each index may hold:</p><ul><li>null (if nothing is stored)</li><li>a single Node</li><li>a <strong>LinkedList</strong> (chain of nodes)</li><li>a <strong>TreeNode (Red-Black Tree)</strong> if collisions cross a threshold</li></ul><p>Here’s a simple ASCII visual:</p><pre>Index:    0      1      2      3      4<br>          --------------------------------<br> Bucket:  null   Node   null   Node → Node → Node   null</pre><h3>3. How Does HashMap Find the Bucket?</h3><p>HashMap uses the key’s hash:</p><pre>hash = key.hashCode()<br>index = (n - 1) &amp; hash</pre><p>This is a fast bitwise operation, not a modulo division.</p><h3>Why &amp;?</h3><p>Because &amp; is faster than %, and the array size is always a power of two.</p><h3>4. Collisions — When Two Keys Land in the Same Bucket</h3><p>A collision happens when two keys produce the same index.</p><p>Example:</p><p>&quot;John&quot; and &quot;Smith&quot; → Both map to bucket 3.</p><p>HashMap handles collisions using:</p><h3>Java 7: LinkedList (always)</h3><h3>Java 8+:</h3><ul><li>LinkedList initially</li><li>When list size &gt; 8 and capacity &gt; 64 → <strong>Converted to Red-Black Tree</strong></li></ul><p>This boosts lookup speed from <strong>O(n)</strong> to <strong>O(log n)</strong>.</p><h3>5. Treeification (Java 8+)</h3><p>When too many entries fall into the same bucket:</p><pre>Bucket 3:<br>   Node → Node → Node → Node → Node → Node → Node → Node → Node<br>                             (More than 8)</pre><p>HashMap converts it into a balanced Red-Black tree:</p><pre>         (root)<br>        /      \<br>     Node      Node<br>     /  \      /   \<br>  Node Node Node  Node</pre><p>This dramatically improves performance.</p><h3>6. Resizing — When HashMap Grows Automatically</h3><p>Default capacity: <strong>16</strong><br> Load factor: <strong>0.75</strong></p><p>When size exceeds <strong>16 × 0.75 = 12</strong>, HashMap <strong>doubles</strong> its size.</p><p>New capacity: <strong>32</strong></p><h3>Resizing causes:</h3><ul><li>New bucket array creation</li><li><strong>Rehashing</strong> of all existing nodes</li><li>Redistribution of entries</li></ul><p>This is an expensive operation.<br> Interview tip: <em>Avoid frequent resizing by initializing HashMap with expected size.</em></p><h3>7. Fast Lookup Process (Step-by-Step)</h3><p>When you call:</p><pre>map.get(&quot;John&quot;);</pre><p>HashMap follows these steps:</p><ol><li>Calculate hash</li><li>Find index</li><li>Check bucket</li><li>If single node and key matches → return value</li><li>If LinkedList → iterate and match</li><li>If tree → navigate using tree rules</li></ol><h3>🧠 8. Interview-Level Summary</h3><p>Here’s a crisp way to explain it:</p><p><em>“HashMap stores data in an array of buckets. The index is computed using </em><em>(n - 1) &amp; hashCode. Collisions are resolved using a LinkedList or, after Java 8, a balanced Red-Black tree for better performance. When size crosses the threshold defined by load factor, the map resizes by doubling its table size and rehashing entries.”</em></p><p>This answer alone gets you a <strong>green flag</strong> in interviews.</p><h3>🎯 Final Thoughts</h3><p>HashMap is simple on the surface but incredibly optimized under the hood.<br> If you understand:</p><ul><li>hashing</li><li>buckets</li><li>collisions</li><li>resizing</li><li>treeification</li></ul><p>…you’re already ahead of many developers.</p><p>This is Day 25 of my <strong>100 Days of Java Core Concepts</strong> series.<br> More deep dives coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7905b8497eda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 24 — Why HashMap Allows One Null Key but Hashtable Doesn’t?]]></title>
            <link>https://medium.com/@ashutosh-ceg/day-24-why-hashmap-allows-one-null-key-but-hashtable-doesnt-34590be27105?source=rss-954d2924e004------2</link>
            <guid isPermaLink="false">https://medium.com/p/34590be27105</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Tiwari]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 16:00:57 GMT</pubDate>
            <atom:updated>2025-11-20T16:00:57.509Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Day 24 — Why HashMap Allows One Null Key but Hashtable Doesn’t?</strong></h3><p>If you’re preparing for Java interviews, this is one of those classic <strong>“simple but deep”</strong> questions.<br> Let’s break it down in a clean, interviewer-friendly way</p><p>HashMap allows ONE null key — Why?</p><p>Because <strong>HashMap is not synchronized</strong> and is designed for <strong>high performance</strong>.</p><p>✔ HashMap uses hashCode() to place keys in buckets<br> ✔ When the key is null, HashMap handles it as a <strong>special case</strong><br> ✔ It simply stores all null keys in <strong>bucket 0</strong><br> ✔ No method call → No NullPointerException</p><p>Meaning: HashMap internally says –<br> <strong>“No hash? No problem. I’ll manage it myself.”</strong></p><p>Hashtable does NOT allow null keys — Why?</p><p>Because <strong>Hashtable is synchronized</strong> and designed for <strong>legacy thread-safe operations</strong>.</p><p>Hashtable calls:</p><pre>key.hashCode()</pre><p>If key == null → BOOM <br> <strong>NullPointerException</strong></p><p>Historically, Hashtable was created before modern Java collections, and designers chose to <strong>reject null to avoid ambiguity in multi-threaded environments</strong>.</p><h3>But why is null ambiguous in Hashtable?</h3><p>Imagine this:<br> If a thread retrieves a value and gets null, does that mean:</p><ul><li>❓ Key wasn’t present?</li><li>❓ Key was present but mapped to null?</li><li>❓ A thread removed it just now?</li></ul><p>This ambiguity was <strong>not acceptable</strong> for early thread-safe collections.</p><p>So <em>Hashtable forbids nulls</em></p><p><em>ConcurrentHashMap also forbids nulls for the same reason</em></p><p>Interview Answer</p><p><strong><em>HashMap allows one null key because it handles null as a special case without calling hashCode(), storing it in bucket 0. Hashtable doesn’t allow null because it uses synchronized methods and calling hashCode() on a null key would cause NullPointerException. Also, null is ambiguous in thread-safe maps, which is why both Hashtable and ConcurrentHashMap disallow null keys and values.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*4hFzdjriz3YNOafoUavr6w.png" /></figure><p><em>Part of my “100 Days of Java” series.</em><br> I share one Java concept each day — explained clearly, practically, and interview-ready.</p><p>👉 Follow me for more:<br> <strong>#100DaysOfJava #JavaInterview #ConcurrentHashMap #SynchronizedMap #Concurrency #JavaPerformance #AshutoshTiwari</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34590be27105" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>