What are the differences between HashMap and Hashtable in Java?

Hashtables and HashMaps are both used to store data in key-value pairs. To store unique keys, both use the hashing approach. However, there are numerous distinctions between the HashMap and Hashtable classes, which are listed below.

HashMap

  1. HashMap is a non-synchronized data structure. It is not thread-safe and cannot be shared among several threads without the use of synchronization code.
  2. One null key and numerous null values are allowed in HashMap.
  3. HashMap is a brand-new class in JDK 1.2.
  4. HashMap is a quick and fast algorithm.
  5. This code can be used to make the HashMap synchronized : Map m = Collections.synchronizedMap(HashMap);
  6. Iterator traverses the HashMap.
  7. HashMap’s iterator is fail-safe.
  8. AbstractMap is inherited by HashMap.

Hashtable

  • Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is a legacy class.
  • Hashtable is slow.
  • Hashtable is internally synchronized and can’t be unsynchronized.
  • Hashtable is traversed by Enumerator and Iterator.
  • Enumerator in Hashtable is not fail-fast.
  • Hashtable inherits Dictionary class.

So, We can say that Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

Hope it helps!