HashMap vs Hashtable in Java
In this lesson: HashMap vs Hashtable — synchronization, null keys, performance — and when to use ConcurrentHashMap. In Hindi & English.
Two key-value maps
HashMap and Hashtable both store key-value pairs, but they differ in thread safety, null handling and speed. HashMap is the modern default; Hashtable is an older, legacy class. Knowing the differences helps you pick correctly.
HashMap
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Aman", 88);
map.put(null, 0); // null key allowed
System.out.println(map.get("Aman"));
HashMap gives fast key-based lookup and allows one null key. It is not thread-safe, which is exactly why it is fast — ideal for normal single-threaded programs.
Hashtable
import java.util.Hashtable;
Hashtable<String, Integer> table = new Hashtable<>();
table.put("Aman", 88);
// table.put(null, 0); // ERROR: no null keys
System.out.println(table.get("Aman"));
Hashtable is thread-safe because all its methods are synchronized. But it does not allow null keys or values, and the synchronization makes it slower.
The key differences
- Thread safety: Hashtable is synchronized; HashMap is not.
- Speed: HashMap is faster (no locking overhead).
- Nulls: HashMap allows one null key and null values; Hashtable allows none.
- Age: Hashtable is legacy; HashMap is the modern choice.
Null keys and values
HashMap<String, String> m = new HashMap<>();
m.put(null, "ok"); // fine in HashMap
m.put("x", null); // fine
// Hashtable would throw NullPointerException on either
HashMap tolerates a null key and null values, which can be handy. Hashtable rejects both, throwing a NullPointerException — a subtle but important difference.
What to use today
- Single-threaded code → HashMap (fast, the common case).
- Thread-safe access → ConcurrentHashMap (modern, efficient).
- Hashtable → generally avoid in new code; it is legacy.
So in practice you rarely reach for Hashtable — HashMap or ConcurrentHashMap covers today's needs.
Common mistakes
- Using Hashtable for new code. Prefer HashMap or ConcurrentHashMap.
- Expecting HashMap to be thread-safe. It is not — use ConcurrentHashMap for that.
- Putting a null key in Hashtable. It throws NullPointerException.
- Expecting insertion order. Neither keeps order; use LinkedHashMap if you need it.
Summary
- Both store key-value pairs; they differ in safety, nulls and speed.
- HashMap is fast, not thread-safe, allows one null key.
- Hashtable is thread-safe, slower, allows no nulls, and is legacy.
- Use HashMap for single-threaded code.
- Use ConcurrentHashMap, not Hashtable, for thread safety.
Next, revise maps in the Collections Framework, or compare sets in HashSet vs TreeSet.
