Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

HashMap

HashMap is available in the java.util package, and it extends the java.util.AbstractMap class while implementing the java.util.Map, java.lang.Cloneable, and java.io.Serializable interfaces.

Important point of java.util.HashMap:

1. We use HashMap to store data in a Key-Value pair.
2. We can store different types of keys and values.
3. Duplicity is allowed in keys, but we can store duplicated values.
4. We can store null values in HashMap as both keys and values.
5. HashMap internally uses an index representation to store its elements.
6. Random access is allowed in HashMap.
7. None of the methods of the java.util.HashMap class are synchronized.
8. Because the java.util.HashMap class implements the Cloneable and Serializable interfaces, it means it is eligible for cloning and serialization.
9. It uses an unordered way to store its elements.
10. We can traverse a HashMap using an Iterator, but List-Iterator is not applicable.

            
import java.util.HashMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put((byte) 101, (byte) 201);
      map.put((short) 202, (short) 202);
      map.put((int) 303, (int) 303);
      map.put((long) 404, (long) 404);
      map.put(12.34 f, 67.89 f);
      map.put(34.56, -678.90);
      map.put(true, false);
      map.put('K', 'V');
      map.put("key", "value");
      map.put(null, null);
      map.put(new JTC(), new JTC());
      System.out.println("map :- " + map);
   }
}
    map :- {null=null, 12.34=67.89, 404=404, 101=-55, com.P1.JTC@515f550a=com.P1.JTC@36aa7bc2, 202=202, K=V, 34.56=-678.9, key=value, 303=303, true=false}
            

In this example, we create an object of the java.util.HashMap class and add various types of data to the newly created HashMap using the put() method.

Important Constrcutor of java.util.HashMap:

1. public java.util.HashMap(): It creates an empty HashMap with an initial capacity of 16, and the default load factor is set to 0.75.

2. public java.util.HashMap(int): It creates an empty HashMap with a specified initial capacity and using the default load factor of 0.75.

3. public java.util.HashMap(int, float): It creates an empty HashMap with a specified initial capacity and a specified load factor of 0.75.

4. public java.util.HashMap(java.util.Map): It creates a HashMap with mappings identical to the specified Map. The initial capacity will be sufficient to hold all the mappings of the specified Map, and the load factor is set to 0.75.

Important Method of java.util.HashMap:

1. Public Object put(Object key, Object value): It adds the specified value along with the specified key to the current working HashMap and returns the previous value associated with the same key. If a new key is being added, it returns null.

            
import java.util.HashMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = new HashMap < > ();
      System.out.println(map.put("K1", "V1"));
      System.out.println("map :- " + map);
      System.out.println(map.put("K1", "V2"));
      System.out.println("map :- " + map);
   }
}
    null
    map :- {K1=V1}
    V1
    map :- {K1=V2}
            

2. public void putAll(java.util.Map): Copies all of the mappings from the specified map to this map. These mappings will replace any existing mappings for keys that are already present in the specified map.

            
import java.util.HashMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      System.out.println("map :- " + map);
      HashMapmap1 = newHashMap();
      map1.put("K6", "V6");
      map1.put("K7", "V7");
      map1.put("K8", "V8");
      System.out.println("map1 :- " + map1);
      map.putAll(map1);
      System.out.println("map.putAll(map1) :- " + map);
      map1.putAll(map);
      System.out.println("map1.putAll(map) :- " + map1);
   }
}
    map :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    map1 :- {K6=V6, K7=V7, K8=V8}
    map.putAll(map1) :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5, K6=V6, K7=V7, K8=V8}
    map1.putAll(map) :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5, K6=V6, K7=V7, K8=V8}
            

3. public Object remove(java.lang.Object); It removes the mapping associated with the specified key from the map and returns the corresponding value. If there is no mapping for the specified key, it returns null.

            
import java.util.HashMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put((byte) 101, (byte) 123);
      map.put((short) 202, (short) 202);
      map.put((int) 303, (int) 303);
      map.put((long) 404, (long) 404);
      map.put(12.34 f, 67.89 f);
      map.put(34.56, -678.90);
      map.put(true, false);
      map.put('K', 'V');
      map.put("key", "value");
      map.put(null, null);
      map.put(new JTC(), new JTC());
      System.out.println("map :- " + map);
      System.out.println(map.remove((byte) 101));
      System.out.println("map :- " + map);
      System.out.println(map.remove("K1"));
   }
}
    map :- {null=null, 12.34=67.89, 404=404, 101=123, com.P1.JTC@515f550a=com.P1.JTC@36aa7bc2, 202=202, K=V, 34.56=-678.9, key=value, 303=303, true=false}
    123
    map :- {null=null, 12.34=67.89, 404=404, com.P1.JTC@515f550a=com.P1.JTC@36aa7bc2, 202=202, K=V, 34.56=-678.9, key=value, 303=303, true=false}
    null
            

4. public boolean remove(java.lang.Object, java.lang.Object): It removes the mapping from the current working Map that contains the specified key and value, and returns true. If there is no such mapping, it returns false.

            
import java.util.HashMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      System.out.println("map :- " + map);
      System.out.println(map.remove("K1", "V1"));
      System.out.println("map :- " + map);
      System.out.println(map.remove("K8", "V8"));
   }
}
    map :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    true
    map :- {K2=V2, K3=V3, K4=V4, K5=V5}
    false
            

5. public java.util.Set keySet(): It returns a Set containing all the keys of the specified Map. It's important to note that when we remove an element from the Set, the corresponding mapping is also removed from the Map, and vice versa. Attempting to add a new element to the Set results in an UnsupportedOperationException.

            
import java.util.HashMap;
import java.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      Setset = map.keySet();
      System.out.println(map);
      System.out.println(set);
      set.remove("K1");
      System.out.println(map);
      System.out.println(set);
      map.remove("K2");
      System.out.println(map);
      System.out.println(set);
      // set.add("K6"); :-java.lang.UnsupportedOperationException
      map.put("K6", "V6");
      System.out.println(map);
      System.out.println(set);
   }
}
    {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    [K1, K2, K3, K4, K5]
    {K2=V2, K3=V3, K4=V4, K5=V5}
    [K2, K3, K4, K5]
    {K3=V3, K4=V4, K5=V5}
    [K3, K4, K5]
    {K3=V3, K4=V4, K5=V5, K6=V6}
    [K3, K4, K5, K6]
            

6. public java.util.Collection values(): It returns all the values of the current working Map as a Collection. If an element is removed from the Collection, the corresponding mapping is also removed from the Map, and vice versa. Attempting to add any element to the Collection results in an UnsupportedOperationException at the time of execution.

            
import java.util.Collection;
import java.util.HashMap;
importjava.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      Collectionc1 = map.values();
      System.out.println(map);
      System.out.println(c1);
      c1.remove("V1");
      System.out.println(map);
      System.out.println(c1);
      map.remove("K2");
      System.out.println(map);
      System.out.println(c1);
      // c1.add("K6"); java.lang.UnsupportedOperationException
      map.put("K6", "V6");
      System.out.println(map);
      System.out.println(c1);
   }
}
    {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    [V1, V2, V3, V4, V5]
    {K2=V2, K3=V3, K4=V4, K5=V5}
    [V2, V3, V4, V5]
    {K3=V3, K4=V4, K5=V5}
    [V3, V4, V5]
    {K3=V3, K4=V4, K5=V5, K6=V6}
    [V3, V4, V5, V6]
            

7. public java.util.Set<java.util.Map$Entry entrySet(); It returns all the mappings of the current working Map as a Set. If an element is removed from the Set, the corresponding mapping is also removed from the Map, and vice versa. Attempting to add any element to the Set results in an UnsupportedOperationException at the time of execution.

            
importjava.util.Collection;
import java.util.HashMap;
import java.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      Setset = map.entrySet();
      // set.add("K2"); --> java.lang.UnsupportedOperationException
      System.out.println("map :- " + map);
      System.out.println("set :- " + set);
   }
}
    map :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    set :- [K1=V1, K2=V2, K3=V3, K4=V4, K5=V5]
            

8. public Object get(java.lang.Object): It returns the mapping with the specified key from the current working Map and returns null if there is no mapping associated with the specified key.

            
importjava.util.Collection;
import java.util.HashMap;
importjava.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      System.out.println(map.get("K1"));
      System.out.println(map.get("K2"));
      System.out.println(map.get("K3"));
      System.out.println(map.get("K4"));
      System.out.println(map.get("K5"));
      System.out.println(map.get("K6"));
   }
}
    V1
    V2
    V3
    V4
    V5
    null
            

Important Method of java.util.AbstractMap:

1. public boolean equals(java.lang.Object): The equals() method is available in the java.util.AbstractMap class, and it compares two maps. It returns true if both maps contain the same mappings; otherwise, it returns false.

            
importjava.util.Collection;
import java.util.HashMap;
importjava.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      map.put("K4", "V4");
      map.put("K5", "V5");
      HashMapmap1 = newHashMap();
      map1.put("K1", "V1");
      map1.put("K2", "V2");
      map1.put("K3", "V3");
      map1.put("K4", "V4");
      map1.put("K5", "V5");
      System.out.println("map :- " + map);
      System.out.println("map1 :- " + map1);
      System.out.println("map.equals(map1) :- " + map.equals(map1));
      HashMapmap2 = newHashMap();
      map2.put("K10", "V1");
      map2.put("K2", "V10");
      map2.put("K3", "V3");
      map2.put("K4", "V4");
      map2.put("K5", "V5");
      System.out.println("map2 :- " + map2);
      System.out.println("map.equals(map2) :- " + map.equals(map2));
   }
}
    map :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    map1 :- {K1=V1, K2=V2, K3=V3, K4=V4, K5=V5}
    map.equals(map1) :- true
    map2 :- {K2=V10, K3=V3, K4=V4, K5=V5, K10=V1}
    map.equals(map2) :- false
            

2. public int hashCode():- This method is available in the java.util.AbstractMap class and returns the hash code of the HashMap. Here, the hash code is defined as the sum of the hash codes of each entry in the entrySet().

            
importjava.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      HashMapmap = newHashMap();
      map.put("K1", "V1");
      map.put("K2", "V2");
      map.put("K3", "V3");
      Sets1 = map.entrySet();
      System.out.println("s1 :- " + s1);
      intsum = 0;
      Iteratoriterator = s1.iterator();
      while (iterator.hasNext()) {
         sum = sum + iterator.next().hashCode();
      }
      System.out.println("sum :- " + sum);
      System.out.println("map.hashCode() :- " + map.hashCode());
   }
}
    s1 :- [K1=V1, K2=V2, K3=V3]
    sum :- 2957
    map.hashCode() :- 2957
            
Internal Working of HashMap:

As we know, a HashMap stores data in the form of Key-Value pairs. Let's delve into the internal workings of HashMap.
When we add an element to a HashMap, it is stored as an object of the java.util.HashMap$Node class, which is a static inner class of the HashMap class.

Internally, HashMap manages an array of nodes to store its elements. When we add an element, an object of the java.util.HashMap$Node class is created, and the index is calculated using the key object. The hash value is determined using the hash(Key) method, a method of the java.util.HashMap class. Subsequently, the index is calculated based on the hash value, representing the position of the current HashMap$Node object in the array of nodes.

static final int hash(Object key) {
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

But the question is, what will happen when the hash value of the key object is greater than the array length? In this case, we will definitely get java.lang.ArrayIndexOutOfBoundsException. So, in order to solve this problem, HashMap reduces the hash value of the key object using an expression, which is:

index = hash(key) & (n-1)

privatestaticintindexFor(inth, intlength) {
returnh& (length-1);
}

For example, when the key is null, the index of the element in the array is 0 because the hash code of null is always 0.
When examining the internal workings of HashMap, it's crucial to understand how HashMap behaves when attempting to store an element with a key that is already present in the map.
As we know, elements are stored in HashMap in the form of java.util.HashMap$Node class objects. The HashMap$Node class contains four instance variables:

final int hash;
final Object key;
Object value;
java.util.HashMap$Node next;

So an object of java.util.HashMap$Node looks like:

In this context, the hash variable contains the generated hash value, the key variable holds the key object of the mapping, the value variable contains the value object of the mapping, and if the entry is the first in the map with the specified key, then the next variable will be null.

Such as:- map.put(null,”V-1”);

When we add an element into the same Map along with bull key such as: map.put(null,”V-2”); than the internal structure will be

In the above diagram, there are two objects of HashMap$Node with the same key, which is null. In this case, the equals() method comes into play, and if the equals() method returns true, then replacement occurs; otherwise, the data is stored as a linked list.