HashMap Class

HashMap Class

In this tutorial, we are going to discuss about HashMap Class in java. HashMap is a class in Java that implements the Map interface, providing a key-value pair storage mechanism. It uses a hash table to store the key-value pairs and allows rapid retrieval of values based on their keys. HashMap does not guarantee the order of its elements.

HashMap Class
  • HashMap classs contains values based on the key. It implements the Map interface.
  • The underlying data structure is Hashtable.
  • Duplicate keys are not allowed but values can be duplicated.
  • Insertion order is not preserved and it is based on hash code of the keys.
  • Heterogeneous objects are allowed for both key and value.
  • null is allowed for keys(only once) and for values(any number of times).
  • It is best suitable for Search operations.

By default HashMap object is not synchronized. But we can get synchronized version by using the following method of Collections class.

public static Map synchronizedMap(Map m1)
Constructors

1. HashMap m=new HashMap();

 Creates an empty HashMap object with default initial capacity 16 and default fill ratio “0.75”.

2. HashMap m=new HashMap(int initialcapacity);

3. HashMap m =new HashMap(int initialcapacity, float fillratio);

4. HashMap m=new HashMap(Map m);

Capture 18
package com.ashok.collections;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyHashMap {
   public static void main(String[] args) {
      HashMap hMap = new HashMap();
      hMap.put("Ashok", 500);
      hMap.put("Vinod", 800);
      hMap.put("Dillesh", 700);
      hMap.put("Naresh", 500);
      System.out.println(hMap);
      System.out.println(hMap.put("Ashok", 1000));
      Set s = hMap.keySet();
      System.out.println(s);
      Collection c = hMap.values();
      System.out.println(c);
      Set s1 = hMap.entrySet();
      System.out.println(s1);
      Iterator itr = s1.iterator();
      while (itr.hasNext()) {
         Map.Entry m1 = (Map.Entry) itr.next();
         System.out.println(m1.getKey() + "......" + m1.getValue());
         if (m1.getKey().equals("Ashok")) {
            m1.setValue(1500);
         }
      }
      System.out.println(hMap);
   }
}

Output

{Ashok=500, Dillesh=700, Vinod=800, Naresh=500}
500
[Ashok, Dillesh, Vinod, Naresh]
[1000, 700, 800, 500]
[Ashok=1000, Dillesh=700, Vinod=800, Naresh=500]
Ashok......1000
Dillesh......700
Vinod......800
Naresh......500
{Ashok=1500, Dillesh=700, Vinod=800, Naresh=500}

That’s all about the HashMap class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

HashMap Class
Scroll to top