Friday, July 29, 2016

Difference between HashMap and HashTable in Java


HashMap and HashTable in java are two important data structures in the Collection Framework which have some common things between them. Both implement Map interface. Both store the data in the form of key-value pairs. Both use Hashing technique to store the elements. But, there also exist significant differences between them. One important difference being the thread safety. HashMap is not thread safe where asHashTable is thread safe. In this post, we will discuss the differences and similarities betweenHashMap Vs HashTable in java.

Difference Between HashMap And HashTable In Java :

1) Thread Safe
HashTable is internally synchronized. Therefore, it is very much safe to use HashTable in multi-threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi-threaded applications without external synchronization. You can externally synchronize HashMapusing Collections.synchronizedMap() method.

2) Inherited From
Though both HashMap and HashTable implement Map interface, but they extend two different classes.HashMap extends AbstractMap class whereas HashTable extends Dictionary class which is the legacy class in java.

3) Null Keys and Null Values
HashMap allows maximum one null key and any number of null values. Whereas HashTable doesn’t allow even a single null key and null value.

4) Traversal
HashMap returns only Iterators which are used to traverse over the elements of HashMap.HashTable returns Iterator as well as Enumeration which can be used to traverse over the elements ofHashTable.

5) Fail-Fast vs Fail-Safe
Iterator returned by HashMap are fail-fast in nature i.e they throw ConcurrentModificationException if theHashMap is modified after the creation of Iterator other than iterator’s own remove() method. On the other hand, Enumeration returned by the HashTable are fail-safe in nature i.e they don’t throw any exceptions if the HashTable is modified after the creation of Enumeration.

6) Performance
As HashTable is internally synchronized, this makes HashTable slightly slower than the HashMap.

7) Legacy Class
HashTable is a legacy class. It is almost considered as due for deprecation. Since JDK 1.5,ConcurrentHashMap is considered as better option than the HashTable.

8) Member of Java Collection Framework
HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK 1.2. But, HashTable was there before JDK 1.2. From JDK 1.2, it has been made to implement Map interface, making it a member of collection framework.

When To Use What?

HashMap is always recommended if you don’t want thread safety. If you want thread safety, use eitherConcurrentHashMap or make HashMap thread safe by using external synchronization throughCollections.synchronizedMap() method. HashTable is not always recommended to use as it is considered as a legacy class.


No comments:

Post a Comment