<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ hashmap - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ hashmap - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 26 Jun 2026 17:32:18 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/hashmap/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Java HashMaps Work – Internal Mechanics Explained ]]>
                </title>
                <description>
                    <![CDATA[ A HashMap is one of the most commonly used data structures in Java, and it's known for its efficiency. Data in a HashMap is stored in the form of key-value pairs. In this article, I will introduce you to HashMaps in Java. We will explore the common o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-java-hashmaps-work-internal-mechanics-explained/</link>
                <guid isPermaLink="false">66b677afa502c749ffbb5c36</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hashmap ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Collection Framework ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Fri, 09 Aug 2024 20:10:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Or_Fa550XaQ/upload/f4d40f1c8e94855d53776a3bb6179673.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A <code>HashMap</code> is one of the most commonly used data structures in Java, and it's known for its efficiency. Data in a <code>HashMap</code> is stored in the form of key-value pairs.</p>
<p>In this article, I will introduce you to <code>HashMap</code>s in Java. We will explore the common operations of <code>HashMap</code> and then delve into how it operates internally. You will gain an understanding of the hash function and how index calculation takes place. Finally, we will look at the time complexities of the operations and touch upon the behavior in a concurrent environment.</p>
<h2 id="heading-what-is-a-hashmap-in-java"><strong>What is a</strong> <code>HashMap</code> in Java?</h2>
<p>A <code>HashMap</code> implements the <code>Map</code> interface, which is part of the Java collection framework. It's based on the concept of Hashing.</p>
<p>Hashing is a technique that transforms an input of arbitrary size into a fixed-size output using a hash function. The generated output is called the hash code and is represented by an integer value in Java. Hash codes are used for efficient lookup and storage operations in a <code>HashMap</code>.</p>
<h2 id="heading-common-operations"><strong>Common Operations</strong></h2>
<p>Like we discussed above, data in a <code>HashMap</code> is stored in the form of key-value pairs. The key is a unique identifier, and each key is associated with a value.</p>
<p>Below are some common operations supported by a <code>HashMap</code>. Let's understand what these methods do with some simple code examples:</p>
<h3 id="heading-insertion"><strong>Insertion</strong></h3>
<ul>
<li><p>This method inserts a new key-value pair to the <code>HashMap</code>.</p>
</li>
<li><p>The insertion order of the key-value pairs is not maintained.</p>
</li>
<li><p>During insertion, if a key is already present, the existing value will be replaced with the new value that is passed.</p>
</li>
<li><p>You can insert only one null key into the <code>HashMap</code>, but you can have multiple null values.</p>
</li>
</ul>
<p>The method signature for this operation is given below, followed by an example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> V <span class="hljs-title">put</span><span class="hljs-params">(K key, V value)</span></span>
</code></pre>
<pre><code class="lang-java">Map&lt;String, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
map.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">1</span>);
map.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">2</span>);
</code></pre>
<p>In the code above, we have a HashMap example where we add a key of type String and value of type Integer.</p>
<h3 id="heading-retrieval"><strong>Retrieval:</strong></h3>
<ul>
<li><p>Fetches the value associated with a given key.</p>
</li>
<li><p>Returns <code>null</code> if the key does not exist in the <code>HashMap</code>.</p>
</li>
</ul>
<p>The method signature for this operation is given below, followed by an example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> V <span class="hljs-title">get</span><span class="hljs-params">(Object key)</span></span>
</code></pre>
<pre><code class="lang-java">Integer value = map.get(<span class="hljs-string">"apple"</span>); <span class="hljs-comment">// returns 1</span>
</code></pre>
<p>In the code above, we're retrieving the value associated with the key <code>apple</code>.</p>
<p>Other common operations include:</p>
<ul>
<li><p><code>remove</code>: Removes the key-value pair for the specified key. It returns <code>null</code> if the key is not found.</p>
</li>
<li><p><code>containsKey</code>: Checks if a specific key is present in the <code>HashMap</code>.</p>
</li>
<li><p><code>containsValue</code>: Checks if the specified value is present in the <code>HashMap</code>.</p>
</li>
</ul>
<h2 id="heading-internal-structure-of-a-hashmap"><strong>Internal Structure of a</strong> <code>HashMap</code></h2>
<p>Internally, a <code>HashMap</code> uses an array of buckets or bins. Each bucket is a linked list of type <code>Node</code>, which is used to represent the key-value pair of the <code>HashMap</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>&lt;<span class="hljs-title">K</span>, <span class="hljs-title">V</span>&gt; </span>{
    <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> hash;
    <span class="hljs-keyword">final</span> K key;
    V value;
    Node&lt;K, V&gt; next;

    Node(<span class="hljs-keyword">int</span> hash, K key, V value, Node&lt;K, V&gt; next) {
        <span class="hljs-keyword">this</span>.hash = hash;
        <span class="hljs-keyword">this</span>.key = key;
        <span class="hljs-keyword">this</span>.value = value;
        <span class="hljs-keyword">this</span>.next = next;
    }
}
</code></pre>
<p>Above, you can see the structure of the <code>Node</code> class which is used to store the key-value pairs of the <code>HashMap</code>.</p>
<p>The <code>Node</code> class has the following fields:</p>
<ul>
<li><p><code>hash</code>: Refers to the <code>hashCode</code> of the key.</p>
</li>
<li><p><code>key</code>: Refers to the key of the key-value pair.</p>
</li>
<li><p><code>value</code>: Refers to the value associated with the key.</p>
</li>
<li><p><code>next</code>: Acts as a reference to the next node.</p>
</li>
</ul>
<p>The <code>HashMap</code> is fundamentally based on a hash table implementation, and its performance depends on two key parameters: initial capacity and load factor. The <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html">original javadocs</a> of the Hash table class define these two parameters as follows:</p>
<ul>
<li><p>The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.</p>
</li>
<li><p>The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.</p>
</li>
</ul>
<p>Let's now try and understand how the basic operations, <code>put</code> and <code>get</code>, work in a <code>HashMap</code>.</p>
<h3 id="heading-hash-function"><strong>Hash Function</strong></h3>
<p>During the insertion (<code>put</code>) of a key-value pair, the <code>HashMap</code> first calculates the hash code of the key. The hash function then computes an integer for the key. Classes can use the <code>hashCode</code> method of the <code>Object</code> class or override this method and provide their own implementation. (Read about the hash code contract <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()">here</a>). The hash code is then XORed (eXclusive OR) with its upper 16 bits (h &gt;&gt;&gt; 16) to achieve a more uniform distribution.</p>
<p>XOR is a bitwise operation that compares two bits, resulting in 1 if the bits are different and 0 if they are the same. In this context, performing a bitwise XOR operation between the hash code and its upper 16 bits (obtained using the unsigned right shift <code>&gt;&gt;&gt;</code> operator) helps to mix the bits, leading to a more evenly distributed hash code.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hash</span><span class="hljs-params">(Object key)</span> </span>{
    <span class="hljs-keyword">int</span> h;
    <span class="hljs-keyword">return</span> (key == <span class="hljs-keyword">null</span>) ? <span class="hljs-number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt;&gt; <span class="hljs-number">16</span>);
}
</code></pre>
<p>Above, you can see the static hash method of the <code>HashMap</code> class.</p>
<p>The idea is to have a unique hash code for each key, but the hash function could produce the same hash code for different keys. This leads to a situation known as a collision. We will see how to handle collisions in the next section.</p>
<h3 id="heading-index-calculation"><strong>Index Calculation</strong></h3>
<p>Once the hash code for a key is generated, the <code>HashMap</code> calculates an index within the array of buckets to determine where the key-value pair will be stored. This is done using a bitwise AND operation, which is an efficient way to calculate the modulo when the array length is a power of two.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> index = (n - <span class="hljs-number">1</span>) &amp; hash;
</code></pre>
<p>Here, we're calculating the index where n is the length of the bucket array.</p>
<p>Once the index is calculated, the key is then stored at that index in the bucket array. However, if multiple keys end up having the same index, it causes a collision. In such a scenario, the <code>HashMap</code> handles it in one of two ways:</p>
<ul>
<li><p>Chaining/Linking: Each bucket in the array is a linked list of nodes. If a key already exists at a particular index and another key gets hashed to the same index, it gets appended to the list.</p>
</li>
<li><p>Treeify: If the number of nodes exceeds a certain threshold, the linked list is converted into a tree (This was introduced in Java 8).</p>
</li>
</ul>
<pre><code class="lang-java"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> TREEIFY_THRESHOLD = <span class="hljs-number">8</span>;
</code></pre>
<p>This is the threshold that determines treeification.</p>
<p>Therefore, it is essential to have a good hash function that uniformly distributes the keys across the buckets and minimizes the chances of collisions.</p>
<p>The retrieval (<code>get</code>) and deletion (<code>remove</code>) operations work similarly to the insertion (<code>put</code>) operation. Here's how:</p>
<ul>
<li><p>Retrieval (<code>get</code>): Computes the hash code using the hash function -&gt; calculates the index using the hash code -&gt; traverses the linked list or tree to find the node with the matching key.</p>
</li>
<li><p>Deletion (<code>remove</code>): Computes the hash code using the hash function -&gt; calculates the index using the hash code -&gt; removes the node from the linked list or tree.</p>
</li>
</ul>
<h3 id="heading-time-complexity"><strong>Time Complexity</strong></h3>
<p>The basic operations of a <code>HashMap</code>, such as <code>put</code>, <code>get</code>, and <code>remove</code>, generally offer constant time performance of O(1), assuming that the keys are uniformly distributed. In cases where there is poor key distribution and many collisions occur, these operations might degrade to a linear time complexity of O(n).</p>
<p>Under treeification, where long chains of collisions are converted into balanced trees, lookup operations can improve to a more efficient logarithmic time complexity of O(log n).</p>
<h3 id="heading-synchronization"><strong>Synchronization</strong></h3>
<p>The <code>HashMap</code> implementation is not synchronized. If multiple threads access a HashMap instance concurrently and iterate over the map, and if any one of the threads performs a structural modification (such as adding or removing a key-value mapping) on the map, it leads to a <code>ConcurrentModificationException</code>.</p>
<p>To prevent this, you can create a thread-safe instance using the <code>Collections.synchronizedMap</code> method.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In summary, understanding the internal workings of a <code>HashMap</code> is crucial for developers to make informed decisions. Knowing how a key is mapped, how collisions happen, and how they can be avoided helps you use the <code>HashMap</code> efficiently and effectively.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
