Difference between Hashmap and Hashtable in Java

This is one of the most important interview question asked to Java programmers. The reason is because collection framework is extensively used while development of the application. Hence, before using any collection class programmers should be aware of the features provided as well as the limitation of the class.  

In this article, you will understand the difference between HashMap and HashTable in Java and its usage in programming. HashMap is one of the most commonly used class to store key-value pair in Java, but sometimes even Hashtable is required to store key-value pair. Let us first understand difference HashMap and HashTable in detail and later we will understand the usage of HashTable and HashMap in programming.

Legacy 

HashMap was introduced in JDK 1.2 and extends AbstractMap class whereas Hashtable is a legacy class which initially was not part of collection framework. Later from JDK 1.2 it became part of Collection framework and implemented Map interface. Dictionary is the super class of Hashtable class.

Synchronized

HashMap is not synchronized whereas Hashtable is synchronized. But you can explicitly synchronize HashMap. Hence, Hashtable is thread-safe whereas HashMap is not thread-safe.

Keys & Values

Hashtable does not allow null keys and null values whereas HashMap allows to store one null key and any number of null values.

Performance

Because the methods of Hashtable are synchronized, Hashtable is much slower, in terms of performance, than HashMap.

Iteration

Hashtable uses Enumeration to iterate over the elements stored in Hashtable object whereas HashMap uses Iterator to iterate over the elements stored in HashMap object. As HashMap uses Iterator which is fail-fast whereas Hashtable uses Enumerator  which is fail-safe.

Usage of Hashtable and HashMap

These are some of the main difference between Hashtable and HashMap in Java. Let us understand their usage. Last year while I was reviewing the code of the product, I found Hashtable used in most of the places in the application. My first question was why Hashtable was used. Does this application use  multi-threading? 

Performance wise it was a big concern because Hashtable is synchronized whereas HashMap is not. So HashMap takes less time as compared to Hashtable. Moreover, Hashtable should be used in multi-threaded environment whereas HashMap should be used in a single threaded environment as it is not thread safe. So before using these classes one should consider whether the application is single threaded or multi-threaded in which these classes is used.

Article tagged as
Author
Author: Amit Gupta
Published On: 17/09/2015
Last revised On: 16/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media