wellnwill Marathahalli Bangalore

HashMap

  • HashMap is implemented based on hash table.
  • The Objects will be inserted based on keys that is why insertion order is not preserved.
  • Keys should be unique.
  • Values can be duplicated.
  • We can insert heterogeneous elements as key and value.
  • HashMap class implements Serializable and Cloneable interface but it doesnot implement RandomAccess interface.
  • HashMap is basically used for search operation.
  • The default capacity is 16.
  • Multiple threads can access HashMap object.
  • HashMap class is non syncronized . If we have a requirement to make HashMap class as sychronized then use synchronizedMap() method of collections class.
  • Searching and insertion is fast.
  • Both key and value can be null.
import java.util.*;
class Test278
{
 public static void main(String args[])
 {
  HashMap hm=new HashMap();
  hm.put("001","John");
  hm.put("002","Robert");
  hm.put("003","Mac");
  hm.put("004","David");
  System.out.println(hm);
  System.out.println(hm.size());
  System.out.println(hm.isEmpty());
  System.out.println(hm.containsKey("100"));
  System.out.println(hm.containsValue("Dav"));
  System.out.println(hm.get("004"));
  
   

  Set sk=hm.keySet();
  Iterator ktr=sk.iterator();
  System.out.println("----Keys----");
  while(ktr.hasNext())
  {
   System.out.println(ktr.next());
  }
Collection c=hm.values();
  Iterator vtr=c.iterator();
  System.out.println("----Values----");
  while(vtr.hasNext())
  {
   System.out.println(vtr.next());
  }
 }
}


 
import java.util.*;
class Test279
{
 public static void main(String args[])
 {
  HashMap hm=new HashMap();
  hm.put("009","John");
  hm.put("002","Robert");
  hm.put("008","Mac");
  hm.put("004","David");
  System.out.println(hm);

  Set s=hm.entrySet();
  Iterator str=s.iterator();
  System.out.println("----travesing----");
 

while(str.hasNext())
  {
   Map.Entry e=(Map.Entry)str.next();
   System.out.println("Keys:"+e.getKey()+"Values:"
   +e.getValue());
   
   if(e.getKey().equals("004"))
   {
    e.setValue("Bob");
   }
  }
  System.out.println(hm);
 }
}




How to get synchronized Map object.

                                                       
import java.util.*;
class SynMap
{
public static void main(String args[])
{
HashMap hm1=new HashMap(50);
Map hm2=Collections.synchronizedMap(hm1);
}
}
Note: hm1 is non-synchronized and hm2 is synchronized.

Footer with Map