Site icon Narayana Tutorial

HashMap

HashMap

Difference between HashMap& Hashtable:-

HashMap

Hashtable

  • No method is synchronized.
  • Performance is fast/ high
  • HashMap objects is not thread safe.
  • Null is allowed for both keys& values.
  • It is non legacy, introduced in 1.2 version.

 

 

  • Every method is the synchronized.
  • Hashtable object is thread safe.
  • Performance is low.
  • Null, we can’t use for keys & value violation leads to NullPointerException.
  • it is legacy& introduced in 1.0 version.

Collections class contain synchronized Map method:-

HashMap m = new HashMap ();

Map m2 = collections. synchronizedMap (m);

Constructors of HashMap:-

  1. HashMap h = new HashMap ();// creates an empty HashMap object, with default initial capacity& default fill ratio 0.7.
  2. HashMap h = new HashMap ( int initial capacity)
  3. HashMap h = new HashMap ( int initialcapacity, float fillratio);
  4. HashMap h = new HashMap ( Map m )
import java. util. *;
Class HashMapDemo
{
Public static void main ( String[] args)
         {
            HashMap m = new HashMap();
            m. put("narayana", 700);
            m. put("anitha", 800);
            m.put("sunny", 200);
            m. put("vighnesh", 500);
            System.out.println(m);
           System.out.println(m.put("venu",1000));//700
            Set s = m.keySet();
            System.out.println(s);
            collection c = m.values();
            System.out.println(c);// 500, 800, 200, 1000
            Set s1 = m.entrySet();
            iterator itr = s1. iterator();
             while ( its.hasNext())
            {
            Map.Entry m1 =( Map.Entry) itr.next();
            System.out.println(m1.getkey().equals("narayana"))
            {
              m1.setvalue(10000);
             }
            }
            System.out.println(m);
            }
}