Java HashMap Class

Do you know?

1. How HashMap increased it’s size?
2. What is the most important role of fillRatio / Load factor ?

HashMap class implements the map interface by using the hashtable.

Java HashMap extends and implements.

extendsAbstractMap Class
implementsMap interface

HashMap class Parameters

Below are the parameters for HashMap class

  • k : It is the type of keys maintained by the map.
  • v : It is the value.

Constructors of HashMap class

HashMap()Used to create a default HashMap.
HashMap(Map m)Used to create a map using the the elements of give map object which is m in the parameter.
HashMap(int capacity)Used to create the HashMap with the given capacity.
HashMap(int capacity, float fillRatio)Used to create the HashMap with the given capacity along with the load factor which also called fillRatio.

***** fillRatio / Load factor: It represents at what level HashMap should increase its own size. For example product of capacity and load factor as (default size) 16 * 0.75 = 12. This represents that after storing the 12th key – value pair into the HashMap , its capacity becomes 32.


How HashMap increase the size.

HashMap double it’s size, after reaching to threshold value (which is calculated by load factor). Example, Suppose HashMap is initialised with the size of 16 and after storing the 12th key – value pair into the HashMap, its capacity becomes 32.


Example of HashMap with code:

import java.util.*;  

class HashMapClass{  

      public static void main(String args[]){  

           // creating the HashMap object

           HashMap<Integer,String> hashMapObject=new HashMap<Integer,String>();  

          // Putting the data in HashMap




           // Iterating the HashMap values

           for(Map.Entry hmEntry:hashMapObject.entrySet()){  

               System.out.println(hmEntry.getKey()+” “+hmEntry.getValue());  






       102 thirdValue
       100 secValue
       101 firstValue


Key Point’s of HashMap class:

1. It may have one null key and multiple null values.
2. It maintain no order.
3. It contain values based on the key.
4. It contains only unique elements.
5. Default capacity is 16 and load factor is 0.75f