Difference between HashMap and Hashtable in Java

In this post, we will discuss the major difference between HashMap and Hashtable in Java.


 

We know that a Map is an object that maps keys to values. Both HashMap and Hashtable are hash-based implementations of java.util.Map interface. In this post, we will discuss some of the major differences between the two:

 
1. HashMap implementation is not synchronized. It is not thread-safe so several threads should not access a HashMap concurrently without proper synchronization code. The HashMap can be synchronized externally in many ways:

a. Wrap the hash map using the Collections.synchronizedMap method at map’s creation time,

b. Encapsulate any code that modifies the map structurally in a synchronized block.

Now only single thread can execute inside the synchronized block at a time which avoids unsynchronized access to the map.

 
On the other hand, Hashtable implementation is synchronized and can be shared between multiple threads without any explicit synchronization code.

Note that since HashMap is not synchronized, it offers better performance than Hashtable.

 
2. Another notable difference between HashMap and Hashtable is that Hashtable does not allow null keys or values whereas HashMap allows one null key and any number of null values. A NullPointerException will be thrown if we try inserting null as a key or as a value in a Hashtable as shown below.

 

Download   Run Code

Output:

Null Value: NullPointerException thrown
Null Key: NullPointerException thrown
{RED=#FF0000, BLACK=#000000}

 
3. Hashtable is legacy class and should not be used if thread-safe implementation is not required. Javadoc recommends to use ConcurrentHashMap in place of Hashtable for thread-safe highly-concurrent implementation and HashMap class otherwise.

 
4. The iterator returned by HashMap and Hashtable class are fail-fast. That means ConcurrentModificationException will be thrown if map is structurally modified after the iterator is created without using the iterator’s remove() method.

Hashtable is also traversed by Enumerator which is not fail-fast. The results are undefined if the Hashtable is structurally modified after the enumeration is created.

 
5. HashMap inherits java.util.AbstractMap class whereas Hashtable inherits java.util.Dictionary class.

 
 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of