HashMap Class

HashMap
  • A HashMap 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);

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}
HashMap Class


Scroll to top