«Back to Home

Core Java

Topics

Difference Between HashMap And Hashtable In Java

In Java, both HashMap and Hashtable are used to store the data in the key and value form. Both are using hashing technique to store the unique keys.

Differentiate between HashMap and Hashtable

There are various differences between HashMap and Hashtable classes, which are,

 HashMap  Hashtable
Java HashMap is non-synchronized. It is not-thread safe and can't be shared between many threads without the proper synchronization code. Java Hashtable is synchronized. It is thread-safe and can be shared with many threads.
HashMap permits one null key and multiple null values. Hashtable doesn't permit any null key or value.
This class is a new class introduced in JDK 1.2. This class is a legacy class.
HashMap is fast compared to Hashtable. Hashtable is slow compared to HashMap.
 
We can make the HashMap synchronized with calling the code, given below-
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
HashMap is traversed by Iterator only. Hashtable is traversed by both Enumerator and Iterator.
Iterator in HashMap is fail-fast. Enumerator in Hashtable is not a fail-fast.
HashMap class extends AbstractMap class. Hashtable class extends Dictionary class.
 
Summary

Thus, we learnt that both HashMap and Hashtable are used to store the data in the key and the value form. Both are using hashing technique to store the unique keys and also learnt their differences in Java.