How HashMap works internally in java : A debug approach
Tags: java, collections, hashmap, interview
Published: 2019-05-03 18:26:27

---
title: How HashMap works internally in java : A debug approach
published: true
description: 
tags: #java #Collections #hashmap #interview
---

Most common interview questions are "How HashMap works in <a href="https://java2blog.com/core-java-tutorial-for-beginners-experienced/" target="_blank" rel="noopener">java</a>", "How get and put method of <a href="https://java2blog.com/hashmap-in-java-with-examples/" target="_blank" rel="noopener">HashMap</a> work internally". Here I am trying to explain internal functionality with an easy example. HashMap is one of the most used <a href="https://java2blog.com/collections-java/">Collections in java</a>.Rather than going through theory, we will start with example first, so that you will get better understanding and then we will see how get and put function work in java.

</div>
<div style="text-align: justify;">Let's take a very simple example. I have a Country class, we are going to use Country class object as key and its capital name(string) as value. Below example will help you to understand, how these key value pair will be stored in hashmap.</div>
<b>1. Country.java </b>
<pre name="code" class="">package org.arpit.java2blog;
public class Country {

	String name;
	long population;

	public Country(String name, long population) {
		super();
		this.name = name;
		this.population = population;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getPopulation() {
		return population;
	}
	public void setPopulation(long population) {
		this.population = population;
	}

	// If length of name in country object is even then return 31(any random number) and if odd then return 95(any random number).
	// This is not a good practice to generate hashcode as below method but I am doing so to give better and easy understanding of hashmap.
	@Override
	public int hashCode() {
		if(this.name.length()%2==0)
			return 31;
		else 
			return 95;
	}
	@Override
	public boolean equals(Object obj) {

		Country other = (Country) obj;
		if (name.equalsIgnoreCase((other.name)))
			return true;
		return false;
	}

}</pre>
If you want to understand more about hashcode and equals method of object, you may refer<b> <a href="http://www.java2blog.com/2014/02/hashcode-and-equals-method-in-java.html" target="_blank" rel="noopener noreferrer">hashcode() and equals() method in java</a></b>

<b>2. HashMapStructure.java</b>(main class)
<pre name="code" class="">import java.util.HashMap;
import java.util.Iterator;

public class HashMapStructure {

	/**
	 * @author Arpit Mandliya
	 */
	public static void main(String[] args) {

		Country india=new Country("India",1000);
		Country japan=new Country("Japan",10000);

		Country france=new Country("France",2000);
		Country russia=new Country("Russia",20000);

		HashMap&lt;Country, String&gt; countryCapitalMap=new HashMap&lt;Country,String&gt;();  
		countryCapitalMap.put(india,"Delhi");  
		countryCapitalMap.put(japan,"Tokyo");  
		countryCapitalMap.put(france,"Paris");  
		countryCapitalMap.put(russia,"Moscow");  

		Iterator countryCapitalIter=countryCapitalMap.keySet().iterator();//put debug point at this line  
		while(countryCapitalIter.hasNext())  
		{  
			Country countryObj=countryCapitalIter.next();  
			String capital=countryCapitalMap.get(countryObj);  
			System.out.println(countryObj.getName()+"----"+capital);  
		}  
	}  


}</pre>
<div style="text-align: justify;">Now put debug point at line 24 and right click on project-&gt;debug as-&gt; java application. Program will stop execution at line 24 then right click on countryCapitalMap then select watch.You will be able to see structure as below.</div>
<div style="clear: both; text-align: center;"><a style="margin-left: 1em; margin-right: 1em;" href="http://3.bp.blogspot.com/-T4TsTlhwaXU/Uwjj9ypm69I/AAAAAAAACsY/J4-a6rxZLLE/s1600/HashMapStructure1.bmp"><img src="https://3.bp.blogspot.com/-T4TsTlhwaXU/Uwjj9ypm69I/AAAAAAAACsY/J4-a6rxZLLE/s1600/HashMapStructure1.bmp" width="640" height="363" border="0" /></a></div>
<div style="text-align: justify;">Now From above diagram, you can observe the following points</div>
<ol style="text-align: left;">
 	<li style="list-style-type: none;">
<ol style="text-align: left;">
 	<li style="text-align: justify;">There is an Entry[] array called table which has size 16.</li>
 	<li style="text-align: justify;">This table stores Entry class's object. HashMap class has an inner class called Entry. This Entry have key value as an instance variable. Let's see structure of entry class Entry Structure.</li>
</ol>
</li>
</ol>
<pre name="code">static class Entry implements Map.Entry
{
        final K key;
        V value;
        Entry next;
        final int hash;
        ...//More code goes here
}</pre>
<ol style="text-align: left;">
 	<li style="text-align: justify;">Whenever we try to put any key value pair in hashmap, Entry class object is instantiated for key value and that object will be stored in above mentioned Entry[](table). Now you must be wondering, where will above created Enrty object get stored(exact position in table). The answer  is, hash code is calculated for a key by calling Hascode() method. This hashcode is used to calculate index for above Entry[] table.</li>
 	<li style="text-align: justify;">Now, If you see at array index 10 in above diagram, It has an Entry object named HashMap$Entry.</li>
 	<li style="text-align: justify;">We have put 4 key-values in hashmap but it seems to have only 2!!!! This is because if two objects have same hashcode, they will be stored at same index. Now the question arises how? It stores objects in the form of LinkedList(logically).</li>
</ol>
So how hashcode of above country key-value pairs are calculated.
<pre name="code">Hashcode for Japan = 95 as its length is odd.
Hashcode for India =95 as its length is odd
HashCode for Russia=31 as its length is even.
HashCode for France=31 as its length is even.

</pre>
Below diagram will explain LinkedList concept clearly.
<div style="clear: both; text-align: center;"><a style="margin-left: 1em; margin-right: 1em;" href="http://1.bp.blogspot.com/-uBsIhju_rS0/Uwjnm9ngraI/AAAAAAAACsk/0NoA3f6iHqI/s1600/HashMapStructure2.bmp"><img src="https://1.bp.blogspot.com/-uBsIhju_rS0/Uwjnm9ngraI/AAAAAAAACsk/0NoA3f6iHqI/s1600/HashMapStructure2.bmp" width="640" height="280" border="0" /></a></div>
So now if you have good understanding of hashmap structure,Lets go through put and get method.

<hr />

<h2><span style="color: #800000;">Put</span></h2>
Let's see the implementation of put method:

</div>
<pre name="code">		/**
		 * Associates the specified value with the specified key in this map. If the
		 * map previously contained a mapping for the key, the old value is
		 * replaced.
		 *
		 * @param key
		 *            key with which the specified value is to be associated
		 * @param value
		 *            value to be associated with the specified key
		 * @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
		 *         if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
		 *         can also indicate that the map previously associated
		 *         <tt>null</tt> with <tt>key</tt>.)
		 */
		public V put(K key, V value) {
			if (key == null)
				return putForNullKey(value);
			int hash = hash(key.hashCode());
			int i = indexFor(hash, table.length);
			for (Entry e = table[i]; e != null; e = e.next) {
				Object k;
				if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) {
					V oldValue = e.value;
					e.value = value;
					e.recordAccess(this);
					return oldValue;
				}
			}

			modCount++;
			addEntry(hash, key, value, i);
			return null;
		}</pre>
<div style="text-align: justify;">now lets understand above code step by step</div>
<ol style="text-align: justify;">
 	<li>Key object is checked for null. If key is null then it will be stored at table[0] because hashcode for null is always 0.</li>
 	<li>Key object's hashcode() method is called and hash code is calculated. This hashcode is used to find index of array for storing Entry object. It may happen sometimes that, this hashcode function is poorly written so JDK designer has put another function called hash() which takes above-calculated hash value as argument. If you want to learn more about hash() function, you can refer <a href="http://www.java2blog.com/2014/02/hash-and-indexfor-method-in-hashmap.html" target="_blank" rel="noopener noreferrer">hash and indexFor method in hashmap</a>.</li>
 	<li>indexFor(hash,table.length)  is used to calculate exact index in table array for storing the Entry object.</li>
 	<li>As we have seen in our example, if two key objects have same hashcode(which is known as <b>collision</b>) then it will be stored in form of linkedlist.So here, we will iterate through our linkedlist.
<ul style="margin-left: 40px; text-align: left;">
 	<li style="text-align: justify;">If there is no element present at that index which we have just calculated then it will directly put our Entry object at that index.</li>
 	<li style="text-align: justify;">If There is element present at that index then it will iterate until it gets Entry-&gt;next as null.</li>
 	<li style="text-align: justify;">What if we are putting same key again, logically it should replace old value. Yes, it will do that. While iterating it will check key equality by calling equals() method(<b>key.equals(k)</b>), if this method returns true then it replaces value object with current Entry's value object.</li>
 	<li>If it did not find the duplicate key, then current Entry object will become first node in linkedlist and current Entry -&gt; next will become an existing first node on that index.</li>
</ul>
</li>
</ol>
<div>

<hr />

<h2><span style="color: #800000;">Get</span></h2>
<b> </b>Lets see implementation of get now:
<pre name="code">/**
	 * Returns the value to which the specified key is mapped, or {@code null}
	 * if this map contains no mapping for the key.
	 *
	 *
	 * More formally, if this map contains a mapping from a key {@code k} to a
	 * value {@code v} such that {@code (key==null ? k==null :
	 * key.equals(k))}, then this method returns {@code v}; otherwise it returns
	 * {@code null}. (There can be at most one such mapping.)
	 *
	 *
	 * A return value of {@code null} does not <i>necessarily</i> indicate that
	 * the map contains no mapping for the key; it's also possible that the map
	 * explicitly maps the key to {@code null}. The {@link #containsKey
	 * containsKey} operation may be used to distinguish these two cases.
	 *
	 * @see #put(Object, Object)
	 */
	public V get(Object key) {
		if (key == null)
			return getForNullKey();
		int hash = hash(key.hashCode());
		for (Entry e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
			Object k;
			if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k)))
				return e.value;
		}
		return null;
	}
</pre>
<div style="text-align: justify;">As you got the understanding on put functionality of hashmap. So to understand get functionality is quite simple. If you pass any key to get value object from hashmap.</div>
<ol style="text-align: justify;">
 	<li>Key object is checked for null. If key is null then value of Object resides at table[0] will be returned.</li>
 	<li>Key object's hashcode() method is called and hash code is calculated.</li>
 	<li>indexFor(hash,table.length)  is used to calculate exact index in table array using generated hashcode for getting the Entry object.</li>
 	<li>After getting index in table array, it will iterate through linkedlist and check for key equality by calling equals() method and if it returns true then it returns the value of Entry object else returns null.</li>
</ol>
<h3 style="text-align: left;">Key points to Remeber:</h3>
<ul style="text-align: left;">
 	<li>HashMap has a inner class called Entry which stores key-value pairs.</li>
 	<li>Above Entry object is stored in Entry[ ](Array) called table</li>
 	<li>An index of table is logically known as bucket and it stores first element of linkedlist</li>
 	<li>Key object's <a href="https://java2blog.com/hashcode-and-equals-method-in-java/" target="_blank" rel="noopener">hashcode</a>() is used to find bucket of that Entry object.</li>
 	<li>If two key object 's have same hashcode , they will go in same bucket of table array.</li>
 	<li>Key object 's equals() method is used to ensure uniqueness of key object.</li>
 	<li>Value object  's equals() and hashcode() method is not used at all</li>
</ul>
<div><span style="text-align: left;">Please go through </span><span style="text-align: left;"> </span><a style="text-align: left;" href="http://www.java2blog.com/2016/07/core-java-interview-questions-and-answers.html" target="_blank" rel="noopener noreferrer">core java interview questions</a><span style="text-align: left;"> and <a href="https://java2blog.com/java-interview-questions/" target="_blank" rel="noopener">java interview questions</a> for more interview questions.

Originally posted on Java2blog with title <a href="https://java2blog.com/how-hashmap-works-in-java/">How HashMap works in java</a>

You may also like</h2>
<ul>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2016/04/hashmap-in-java-with-examples.html">HashMap in java</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2014/02/how-hashmap-works-in-java.html">How HashMap works in java</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2014/02/hash-and-indexfor-method-in-hashmap.html">hash and indexfor method in HashMap</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2014/02/hashcode-and-equals-method-in-java.html">hashcode and equals method in java</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2016/05/how-to-sort-hashmap-in-java-by-keys-and.html">How to sort HashMap by keys and values</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2013/02/difference-between-hashmap-and-hashset.html">Difference between HashMap and Hash</a><a href="http://www.java2blog.com/2013/02/difference-between-hashmap-and-hashset.html">Set</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2013/02/difference-between-hashtable-and-hashmap.html">Difference between HashMap and Hashtable</a></li>
 	<li dir="ltr" style="text-align: left;"><a href="http://www.java2blog.com/2015/06/how-to-iterate-over-map-or-hashmap-in.html">How to iterate over HashMap</a></li>
</ul>