HashMap vs HashTable: Difference Between HashMap and HashTable in Java

In this article, we will discuss the difference between HashMap and HashTable in Java.

In Java, both HashMap and HashTable are two important data structures in the Collection Framework that have some common things between them. Both implement a 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. In this article, let's discuss the differences between HashMap and HashTable.

Difference Between HashMap And HashTable In Java

1. Synchronization (Thread Safe)

The primary difference between HashMap and Hashtable is synchronization. HashTable is a thread-safe class and can be shared between multiple threads, while HashMap is not thread-safe. 

Well, HashMap is not thread safe so don't use HashMap in multi-threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.

Example of using Hashtable:

Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(1, "Value1");
hashtable.put(2, "Value2");

Example of using HashMap:

HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Value1");
hashMap.put(2, "Value2");

2. Null keys and Null values 

HashTable doesn't allow null keys or null values, while HashMap allows one null key and any number of null values.

For example, HashMap allows one null key and any number of null values:

HashMap<Integer, String> hashMap = new HashMap<>(); 
hashMap.put(null, "Value");  // This is fine 
hashMap.put("key", null);  // This is fine 
hashMap.put("key1", null);  // This is fine 

Hashtable doesn't allow null keys or null values. If you try to pass a null value then it will NullPointerException:

Hashtable<Integer, String> hashtable = new Hashtable<>(); 
hashtable.put(null, "Value");  // This throws NullPointerException

3. Performance 

Since Hashtable is thread-safe, it ensures that no two threads can modify their content at the same time. This thread safety comes at a cost - reduced performance. On the other hand, HashMap, which is not thread-safe, is generally faster than Hashtable.

4. Iterating the values 

HashMap provides a fail-fast iterator, meaning if one thread changes the map structurally by adding or removing elements, it will throw ConcurrentModificationException. But the Hashtable enumerator does not throw ConcurrentModificationException

Here is an example of iterating over HashMap using keySet that throws a ConcurrentModificationException:

import java.util.*;

public class Main {
    public static void main(String[] args) {

        HashMap<Integer,String> hashMap=new HashMap<Integer,String>();
        hashMap.put(1,"Value1");
        hashMap.put(2,"Value2");
        
        Iterator<Integer> iterator=hashMap.keySet().iterator();
        while(iterator.hasNext()){
            hashMap.remove(iterator.next());    // This throws ConcurrentModificationException
        }
    }
}

Output:

Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1605)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1628)
at Main.main(Main.java:12)

Here is an example of iterating over Hashtable using keySet without throwing a ConcurrentModificationException:

import java.util.Hashtable;

public class Main {
    public static void main(String[] args) {

        // create hashtable
        Hashtable<String, Integer> hashtable = new Hashtable<>();

        hashtable.put("one", 1);
        hashtable.put("two", 2);
        hashtable.put("three", 3);

        // iterate over hashtable
        for(String key : hashtable.keySet().toArray(new String[0])) {
            System.out.println(key);

            // try to modify hashtable while iterating
            hashtable.put("four", 4);
        }

        // print the modified hashtable
        System.out.println("Modified Hashtable: " + hashtable);
    }
}

Output:

two
one
three
Modified Hashtable: {two=2, one=1, three=3, four=4}

HashMap provides an iterator, which is fail-fast (it throws a ConcurrentModificationException if the map is modified while being iterated). HashTable, on the other hand, provides an enumerator, which is not fail-fast. 

5. Legacy Class 

HashTable is a legacy class, introduced in the original version of Java, JDK 1.0. HashMap is a much newer class, introduced with the Java Collections Framework in JDK 1.2. 

6. Inherited From 

Though both HashMap and HashTable implement a Map interface, they extend two different classes. HashMap extends AbstractMap class where as HashTable extends the Dictionary class which is the legacy class in Java.

When to Use HashMap And HashTable in Java?

When choosing between a HashMap and a HashTable in Java, the following factors are worth considering: 
1. Synchronization and Thread-Safety: If you're working in a multithreaded environment where multiple threads might modify your map simultaneously, a HashTable could be a better choice because it's thread-safe. However, keep in mind that synchronization comes with a performance cost. If you don't need to worry about multiple threads, or if you're managing synchronization at a higher level in your application, HashMap would be the better choice because it's faster when it doesn't need to manage synchronization. 

2. Null Keys and Values: If you need to store null keys or values, then HashMap is the way to go as HashTable doesn't allow null keys or values. 

3. Performance: HashMap is generally faster and uses less memory than HashTable because it doesn't have to manage synchronization. 

4. Iteration: HashMap provides an iterator, which is fail-fast (it throws a ConcurrentModificationException if the map is modified while being iterated). HashTable, on the other hand, provides an enumerator, which is not fail-fast. 

5. Legacy Code: If you're dealing with older code (pre-Java 4), HashTable might be present because HashMap wasn't introduced until Java 4. 

In most modern, single-threaded Java applications, HashMap will be a better choice due to its performance advantages and flexibility in allowing null keys and values. For multithreaded applications, consider using ConcurrentHashMap or managing synchronization at a higher level while using HashMap if the map will be modified by multiple threads.

Cheat Sheet: HashMap vs HashTable

Comments