Difference between HashMap and HashTable in Java

  • HashTable and HashMap are two hash based collection in Java that uses key value pair to store objects. 
  • Despite being hash based and similar in functionality there are significant differences between Hashtable and HashMap and without understanding those difference some time a programer may lead to servere issues
  • Before seeing differences between HashMap and Hashtable let's see some common similarities between HashMap and Hashtable.

Similarities between HashTable and HashMap

There are some similarities between HashTable and HashMap in Java which may help you in understaning both and then lead you to exact differences between HashTable and HashMap. 
  • Both HashTable and HashMap implements java.util.Map interface. 
  • HashTable and HashMap both are hash based collection and works on principle of hashing.
  • HashTable and HashMap both uses Key, value pairs for storing values.

Differences between HashTable and HashMap

Despite being so similar there are some differences between HashTable and HashMap which separates them completely:  
  • HashTable is a legacy class that came along with the first version of java development kit (JDK), while HashMap was introduced in java version 1.2, as part of java collections framework. 
  • HashTable is synchronized (Thread safe), but HashMap not synchronized. All the new implementations of java collection framework is not synchronized. 
  • As HashTable is synchronized (Thread safe), so in general, executing a ‘synchronized’ method results in costly performance than a unsynchronized method. So HashTable is relatively slower in performance than HashMap. If thread safety in not concerned,  HashMap always perform better than HashTable.
  • HashMap can be synchronized using the java collections framework utility class. Or you can use ConcurrentHashMap in case of multi-threaded environment.
  • HashTable doesn't allow Null key however HashMap allows Null key and values.

No comments:

Post a Comment