Wednesday, March 30, 2016

How HashMap works in Java ?

HashMap :


    • HashMap is class from java.util pacakge.
    • It stores key value pair in Map.Entry static nested class implementation.
    • It maintain only unique key's, one null value is allowed as a key.
    • If any key is already present with some value and other key is put with new value then current value of that key get overwrite with new value.
    •  HashMap is not synchronized.
Example :
package interviewdev.blogspot.in;

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {

 public static void main(String[] args) {
   
    HashMap hm=new HashMap();  
    
    hm.put(1,"Amit");  
    hm.put(2,"Virat");  
    hm.put(3,"Dhoni");  
    
    for(Map.Entry m:hm.entrySet()){  
     System.out.println(m.getKey()+" "+m.getValue());  
    }  

 }

}


  • A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode() and equals() functions of Object class, in order to put and retrieve elements to and from the collection respectively.
  • When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry. 
  • When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. 
  • Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.
  • HashMap initial default capacity is 16 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pair.
  • Below image will explain these detail clearly.

How HashMap works internally ?

HashMap works on the Principal of Hashing. To understand hashing we must understand Hash Function , Hash Value and Bucket. Let's understand each of them.

Hash Function and Hash Value:


  • hashCode() function  which returns an integer value is the Hash function
  • The code for the hashCode() in Object class is as follow :


         public native int hashCode();
  • The integer value returned by the above function is known as Hash value.
Bucket : 
  • A bucket is used to store key-value pairs.
  • In HashMap bucket is Linked List (Simple Linked List for HashMap).







No comments:

Post a Comment