HomeJavaWhat is the Difference between HashMap and HashTable?

What is the Difference between HashMap and HashTable?

One of the frequently asked interview question for Java/J2EE professionals is “What is the Difference between HashMap and HashTable?”. In this journal, we will digging deep into understanding the major differences between a HashMap and HashTable.

DJ Recommended Reads:

HashMap vs HashTable

[table id=3 /]

Another difference between these classes is that the Iterator of the HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except iterator’s own remove() method. In Simple words fail-fast means: When calling iterator.next(), if any modification has been made between the moment the iterator was created and the moment next() is called, a ConcurrentModificationException is immediately thrown.

Enumerator for the Hashtable is not fail-fast.

For e.g.


HashMap hm= new HashMap();
Set keys = hm.keySet();
for (Object key : keys) {
    //it will throw the ConcurrentModificationException here
    hm.put(object & value pair here); 


Hashtable ht= new Hashtable();
Enumeration keys = ht.keys();
 for (Enumeration en = ht.elements() ; en.hasMoreElements() ; en.nextElement()) {
      //No exception would be thrown here
      ht.put(key & value pair here); 

DJ Recommended Reads:

When to use HashMap and Hashtable?

As stated above the main difference between HashMap & Hashtable is synchronization. If there is a need for thread-safe operation then HashTable can be used as all its methods are synchronized but it’s a legacy class and should be avoided as there is nothing about it, which cannot be done by HashMap. For the multi-threaded environment, we would recommend you to use ConcurrentHashMap (almost similar to Hashtable) or even you can make the HashMap synchronized explicitly.

Synchronized operation gives the poor performance so it should be avoided until unless required. Hence for a non-thread environment, HashMap should be used without any doubt.


Please enter your comment!
Please enter your name here

Most Popular