What is the differences between HashMap and HashTable in Java

Java 8Object Oriented ProgrammingProgramming

HashMap and HashTable both are one of the most important classes of Java Collection framework. Both HashMap and HashTable stores the data in key value pair and at the time storing data hashing is used to hash the key and the resulting hash code is used as the index at which the value is stored within the table. But still, there are many differences between both these classes which we would discuss below.

The following are the important differences between HashMap and HashTable.

Sr. No.KeyHashMapHashTable
1IntroductionHashmap is the advanced version of HashTable and is introduced as a new class in JDK 1.2.HashTable on the other hand is the legacy class and was introduced prior to HashMap.
2Internal implementationInternal implementation of both classes is same upto some extent but in case of HashMap one null key and multiple null values are allowed.HashTable internally implemented in such manner that it does not allow any null key or any null value.
3SynchronizationSynchronization is not implemented in HashMap and is not thread safe so can't be shared between many threads without proper synchronization code.On the other hand, HashTable is synchronized and is thread safe so can be shared with many threads.
4Traversed the elementsHashMap provides Iterator for its iteration in order to traverse the values stored in it.On the other hand along with Iterator HashTable also provides Enumerator to traverse the values stored in it.
5Index performanceDue to the absence of synchronization HashMap is faster as compare to HashTable and is preferred when synchronization is not needed.Synchronization in HashTable makes it slower as compare to HashMap but also eliminate the writing of extra code to obtain the synchronization.
6InheritanceHashMap inherits AbstractMap class.On the other hand, HashTable inherits Dictionary class.

Example of HashMap vs HashTable


import java.util.*;
import java.lang.*;
import java.io.*;
public class JavaTester{
   public static void main(String args[]){
      Hashtable ht=new Hashtable();
      System.out.println("-------------Hash table--------------");
      Set<Integer> keySet = ht.keySet();
      for (Integer key:keySet) {
         System.out.println(key + " "+ht.get(key));
      HashMap hm=new HashMap();
      hm.put(104,"John"); // hash map allows duplicate values
      System.out.println("-----------Hash map-----------");
      Set<Integer> keySet1 = ht.keySet();
      for (Integer key:keySet) {
         System.out.println(key + " "+hm.get(key));


-------------Hash table--------------
103 Andy
102 Smith
101 Jhony
-----------Hash map-----------
100 John
101 Smith
102 Andy
104 John
Published on 18-Sep-2019 13:50:45