0
0
JavaComparisonBeginner · 3 min read

HashMap vs Hashtable in Java: Key Differences and Usage

HashMap and Hashtable are both map implementations in Java, but Hashtable is synchronized (thread-safe) while HashMap is not. Also, HashMap allows null keys and values, whereas Hashtable does not.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of HashMap and Hashtable based on key factors.

FactorHashMapHashtable
Thread SafetyNot synchronized (not thread-safe)Synchronized (thread-safe)
Null Keys and ValuesAllows one null key and multiple null valuesDoes not allow null keys or values
PerformanceFaster due to no synchronization overheadSlower due to synchronization
Legacy StatusIntroduced in Java 1.2 (part of Collections Framework)Legacy class from Java 1.0
Iterator TypeFail-fast iteratorEnumerator (not fail-fast)
Use CaseSingle-threaded or externally synchronizedMulti-threaded without external synchronization
⚖️

Key Differences

Hashtable is a legacy class that is synchronized, meaning it is thread-safe by default. This synchronization causes overhead, making it slower in single-threaded environments. In contrast, HashMap is not synchronized, so it performs better but requires external synchronization if used in multi-threaded contexts.

Another important difference is how they handle null values. HashMap allows one null key and multiple null values, which can be useful for some applications. Hashtable does not allow any null keys or values and will throw a NullPointerException if you try to insert them.

Additionally, HashMap is part of the modern Java Collections Framework introduced in Java 1.2, while Hashtable is older and considered legacy. The iterators returned by HashMap are fail-fast, meaning they throw an exception if the map is modified during iteration, whereas Hashtable uses enumerators which are not fail-fast.

⚖️

Code Comparison

Here is how you create and use a HashMap to store and print key-value pairs.

java
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("apple", "red");
        map.put("banana", "yellow");
        map.put(null, "unknown");

        for (String key : map.keySet()) {
            System.out.println(key + " -> " + map.get(key));
        }
    }
}
Output
null -> unknown apple -> red banana -> yellow
↔️

Hashtable Equivalent

Here is the equivalent code using Hashtable. Note that null keys or values are not allowed.

java
import java.util.Hashtable;

public class HashtableExample {
    public static void main(String[] args) {
        Hashtable<String, String> table = new Hashtable<>();
        table.put("apple", "red");
        table.put("banana", "yellow");
        // table.put(null, "unknown"); // This would throw NullPointerException

        for (String key : table.keySet()) {
            System.out.println(key + " -> " + table.get(key));
        }
    }
}
Output
apple -> red banana -> yellow
🎯

When to Use Which

Choose HashMap when you need better performance and are working in a single-threaded environment or can handle synchronization externally. It is more flexible with null keys and values and is the preferred modern choice.

Choose Hashtable only if you need a thread-safe map without external synchronization and are working with legacy code. However, consider using ConcurrentHashMap instead for better concurrency support in multi-threaded applications.

Key Takeaways

HashMap is not synchronized and allows null keys and values, making it faster and more flexible.
Hashtable is synchronized and thread-safe but does not allow null keys or values, causing slower performance.
Use HashMap for most modern applications unless thread safety without external synchronization is required.
For multi-threaded environments, prefer ConcurrentHashMap over Hashtable for better concurrency.
Hashtable is a legacy class and generally discouraged in new code.