How hashmap works in java

Most of you will agree that HashMap is most favorite topic for discussion in interviews now-a-days. I have gone through several discussions with my colleagues time to time and it really helped. Now, I am continuing this discussion with you all.

I am assuming that if you are interested in internal working of HashMap, you already know basics of HashMap, so i am skipping that part. But if you are new to concept, follow official java docs.

Before moving forward, i will highly recommend reading my previous post : Working with hashCode and equals methods in java

Sections in this post
    1) Single statement answer
    2) What is Hashing
    3) A little about Entry class
    4) What put() method actually does
    5) How get() methods works internally
    6) Key Notes

Single statement answer

If anybody asks me to describe “How HashMap works?“, I simply answer: “On principle of Hashing“. As simple as it is. Now before answering it, one must be very sure to know at least basics of Hashing. Right??

What is Hashing

Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

Read more here : Working with hashCode() and equals() methods in java

A little about Entry class

A map by definition is : “An object that maps keys to values”. Very easy.. right?

So, there must be some mechanism in HashMap to store this key value pair. Answer is YES. HashMap has an inner class Entry, which looks like this:

static class Entry implements Map.Entry
{
        final K key;
        V value;
        Entry next;
        final int hash;
        ...//More code goes here
}

Surely Entry class has key and value mapping stored as attributes. Key has been marked as final and two more fields are there: next and hash. We will try to understand the need of these fields as we go forward.

What put() method actually does

Before going into put() method’s implementation, it is very important to learn that instances of Entry class are stored in an array. HashMap class defines this variable as:

   /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry[] table;

Now look at code implementation of put() method:

[sourcecode language="java"]
/**
* 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<k , V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((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;
}
[/sourcecode]

Lets note down the steps one by one:

– First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.

– Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function, and passed the object’s hash code to this hash() function to bring hash value in range of array index size.

– Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.

– Here comes the main part. Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket].
Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.

So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.

If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.

What if we add the another value object with same key as entered before. Logically, it should replace the old value. How it is done? Well, after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.

In this way, HashMap ensure the uniqueness of keys.

How get() methods works internally

Now we have got the idea, how key-value pairs are stored in HashMap. Next big question is : what happens when an object is passed in get method of HashMap? How the value object is determined?

Answer we already should know that the way key uniqueness is determined in put() method , same logic is applied in get() method also. The moment HashMap identify exact match for the key object passed as argument, it simply returns the value object stored in current Entry object.

If no match is found, get() method returns null.

Let have a look at code:

[sourcecode language="java"]
/**
* Returns the value to which the specified key is mapped, or {@code null}
* if this map contains no mapping for the key.
*
* <p>
* 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.)
*
* </p><p>
* 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<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
[/sourcecode]

Above code is same as put() method till if (e.hash == hash && ((k = e.key) == key || key.equals(k))), after this simply value object is returned.

Key Notes

  1. Data structure to store Entry objects is an array named table of type Entry.
  2. A particular index location in array is referred as bucket, because it can hold the first element of a LinkedList of Entry objects.
  3. Key object’s hashCode() is required to calculate the index location of Entry object.
  4. Key object’s equals() method is used to maintain uniqueness of Keys in map.
  5. Value object’s hashCode() and equals() method are not used in HashMap’s get() and put() methods.
  6. Hash code for null keys is always zero, and such Entry object is always stored in zero index in Entry[].

I hope, i have correctly communicated my thoughts by this article. If you find any difference or need any help in any point, please drop a comment.

Happy Learning !!

118 thoughts on “How hashmap works in java”

  1. hi Lokesh, just tell me hashmap internally uses overriding equals() and hashCode().is there any situation where we need to write these two methods in our hashmap program ???or only hashmap internally uses it???

  2. Hi Lokesh… I found below paragraph on blogspot.com for the same question.

    While rehashing, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap, the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because HashMap doesn’t append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop.

    Please explain above paragraph. I failed to understand below points –
    1. Why list is getting reversed while rehashing. I mean what advantage we got ?
    2. Why elements are getting added at front end of list ? Why not tail end ?

  3. hi
    i just want to know that looping through the hashmap would be faster or through a for loop. I think for loop but just need an expert opinion on this.

  4. The article is really helpful Lokesh.
    I have a querry,
    you said objects are stored in LinkedList in a single bucket. is it like this
    K!V–>K!V–>null
    ?
    Pkease clarify.

  5. Is it possible to write a program in which we can put all elements in same bucket. like overiding some of the methods..

    1. Absolutely. Look at the sourcecode. public Object put(Object obj, Object obj1) is public so you can override it. It uses indexFor(i, table.length) method call for getting the index location. Pass two constants values in this function and it will return the same location everytime; means all elements in same bucket.
      But other operations does not seem so simple. You will need to override a lot of methods to work it properly.

  6. Hello Lokesh,

    Thanks for sharing this nice article. I have a small doubt or say disagreement regarding put method explanation here –

    “So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.

    If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.”

    [java]
    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<k , V> e = table[i]; e != null; e = e.next) {
    Object k;
    if (e.hash == hash && ((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;
    }

    [/java]

    So, that for loop in the put will run on a LinkedList at a particular bucket index, and the only purpose of that for loop is to identify if key already exists and if it is replace that and return the old value.

    and if key doesn’t exist it will invoke [java] addEntry(hash, key, value, i); [/java]

    i.e it will add entry to the head of linkedlist.

    Hope you got my point, Please let me know if above explanation has some flaws ?

    1. Hi Saurabh, yes you are right. Correct wording should be “added to head of linkedlist”. Thanks for suggesting this small but critical language change.

  7. Hi Lokesh,
    Your article is very informative. I just have one question.
    If the state of an object is changed, the hashCode of that object will be re-calculate and changed automatically or will stay same until calculated again explicitly?

      1. Great care must be exercised if mutable objects are used as set
        * elements. The behavior of a set is not specified if the value of an object
        * is changed in a manner that affects equals comparisons while the
        * object is an element in the set,,,,,,, Does the same not apply for Map

  8. Hi Lokesh,
    It’s the best explanation I ever came across. I have a small doubt. You mentioned in one of your above notes:
    “If they have different hashcodes, they may or may not be in same bucket. Anything is possible. You see if there are 100 objects, all having different hashcodes. Will you need a hashtable of size 100?? NO. you do not need. You can accommodate them in a hashtable of size 10 also. It means some of objects with different hashcodes will come into single bucket.”.

    How is this implemented ? if there are 100 objects, all having different hashcodes, then how can they go on same/single bucket (Entry type array’s element) ???

  9. Hi sir,Iam Having Small Doubt related to Map.Question is like,if hashmap found 2 same keys,then it will override old value with the latest value .but before overriding with new value,is it possible to take or collect the old value from hashmap sir.Correct me if iam Wrong.Thanks Venkata Sriram

    1. Hi Venkata, It’s really good question. And infact easy as well. If you go through java docs of HashMap the put() method is given as:

      public V put(K key, V value)
      Parameters:
      key – key with which the specified value is to be associated
      value – value to be associated with the specified key
      Returns:
      the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

      It returns the old value associated with key; IF any. I quickly ran below lines to write an example:

      [java]
      public static void main(String[] args)
      {
      HashMap<String, String> map = new HashMap<String, String>();
      System.out.println(map.put("data", "initial value"));
      System.out.println(map.put("data", "new value"));
      }
      [/java]

      It outputs as:

      null
      initial value

      So, when you write the “new value” then it returns the “initial value”.

  10. Rakesh ,

    What is important is not only the hashcode but the number of buckets(Entry table array element is called bucket).Depending on the size of HashMap ie the number of buckets, the objects hashcode , hash and indexFor function will try to put the object in one of the buckets. In case of HashMap of size 16 only lower 4 bits of hash value is considered and in case of size 32 lower 5 bits are considered for &(byte operator) in indexFor function.I have done analysis of the same.
    Please check this blog for a demo of what I have mentioned above. Lokesh , Please correct me if my understanding is wrong somewhere.

    http://ganeshrashinker.blogspot.in/

  11. Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

    I disagree to the above statement. It is simply not possible…

    Lets say, I have an Employee class….

    ANd I create 1 trillion trillion different objects of Employee class.
    But HashCode range is limited to the size of Integer in java..

    So there will be 2 different objects, which will have same hashcode…So the statement you’ve given above, cannot be always applied… Though it can be strived to do so.

    1. Hi Yogesh, there are other things to consider as well i.e. garbage collection. You will need a really big heap to store so many objects, and other objects to keep them referenced so that GC should not claim them to free memory. I am pretty sure that you will get OutOfMemoryError much before trying to create so many objects.
      Another argument can be that hashCode() comes into consideration only when you store all these objects in hash backed collection such as HashMap. As HashMap uses fixed length array to store key-value pairs, then the array size will require a continuous memory location of really big size. It will again result in OutOfMemoryError.

  12. when i put three object a1,a2,a3 in the hash map how they store in table? my doubt is when i get a1 than no equals will call but i get a2 than equals call one times and when i get a3 than equals will call two time why and how???

    I have create class A and override equals that will return false and hashcode return 1.

  13. Hashmap values of existing keys getting overwritten upon using put to store a new key-value pair. how to prevent it?

  14. Hi Lokesh Nice Explaination. Could you please tell me what is the default size of the Entry[] table array?Thanks.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?