Difference between HashMap and Hashtable in java

In this post, we will see the difference between HashMap and Hashtable in Java. First, we will see HashMap vs Hashtable in brief later we will see each point in details.

Difference between HashMap and Hashtable in java

HashMapHashtable
1.HashMap class implements Map interface and extends AbstractMap class.1.Hashtable class implements Map interface and extends Dictionary class.
2.HashMap introduced in jdk1.2.2.Hashtable introduced in jdk1.0 as legacy class(Don't get confused Legacy classes and interfaces introduced in the earlier versions of Java like Vector/Hashtable etc).
3.HashMap is not-thread safe because all methods inside HashMap are non synchronized.3.Hashtable is thread safe because all methods of Hashtable are synchronized
4.HashMap has initial capacity 16 and load factor is 0.75f.4.Hashtable has intial cappacity 11 and load factor is 0.75f.
5.HashMap is fast.5.Hashtable is slow
6. HashMap can have one null as key and multiple null values.6.Hashtable doesnot allow null as key or value.

 

 

HashMap class implements Map interface and extends AbstractMap class whereas Hashtable class implements Map interface and extends Dictionary class.

 

 

 

 

HashMap methods are not synchronized whereas all methods of Hashtable is synchronized. Let’s see put() method for HashMap and Hashtable.

Hashtable put method is synchronized. Similarly, if you look into all other methods of Hashtable, those all are synchronized.

 

HashMap has initial capacity 16 and load factor is 0.75f whereas Hashtable has initial capacity 11 and load factor is 0.75f.

Let’s see how initial capacity has been defined in HashMap class.

 

In case of Hashtable¬† –

 

HashMap is fast whereas Hashtable is slow.

Let’s see an example which illustrates how HashMap is faster than Hashtable.

 

Output is –

time taken by HashMap 21
time taken by Hashtable 54

That’s all about Difference between HashMap and Hashtable in java.

You may like.

See HashMap and Hashtable docs.

Top