Wednesday, February 21, 2007

Difference between HashTable and HashMap

1 comment:

Contact: highbrow.admin@gmail.com said...

1. The HashMap class is roughly equivalent to Hashtable, except that HashMap unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized and Hashtable is synchronized.

When we will try to add null to Hashtable:

Hashtable ht=new Hashtable();
ht.put(null,null);
it compiles properly but give a run time error java.lang.NullPointerException

When we will try to add null to HashMap it accepts it and runs properly.
One thing to note here in HashMap is that you can store null more then once but:
In both Hashtable and HashMap if we will add a key again then only the recently added key is stored in it and the earlier key and value is replaced.

Hashtable ht=new Hashtable();
ht.put("dilip","puja");
ht.put("dilip","sonu");

ht.get("dilip"); // will return "sonu" and not "puja".

Source>>