What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implement the Map interface and store key-value pairs using a hash table, but they differ in synchronization, null handling, and historical context.
Hashtable is a legacy class from Java 1.0. Every public method is synchronized, meaning only one thread can access the table at a time. This makes Hashtable thread-safe but slow — every operation acquires a monitor lock on the entire object, even reads. Hashtable does not allow null keys or null values.
HashMap was introduced in Java 1.2 as part of the Collections Framework. It is not synchronized, making it faster in single-threaded scenarios. HashMap allows one null key and any number of null values.
The critical follow-up: what should you use for thread-safe map operations? ConcurrentHashMap, not Hashtable. ConcurrentHashMap uses fine-grained locking (node-level CAS operations in Java 8+), allowing multiple threads to read and write concurrently without blocking each other. It also provides atomic compound operations like putIfAbsent() and computeIfAbsent().
Another option is Collections.synchronizedMap(), which wraps a HashMap with synchronized methods — similar to Hashtable's coarse-grained locking but returns a standard Map interface.
HashMap's iterators are fail-fast (throw ConcurrentModificationException on structural modification during iteration). ConcurrentHashMap's iterators are weakly consistent — they reflect some changes and never throw ConcurrentModificationException.
There is essentially no reason to use Hashtable in modern Java code.
| Aspect | HashMap | Hashtable |
|---|---|---|
| Synchronization | Not synchronized | All methods synchronized |
| Null keys/values | One null key, many null values | No nulls allowed |
| Performance | Faster (no locking overhead) | Slower (coarse-grained locking) |
| Introduced in | Java 1.2 (Collections Framework) | Java 1.0 (legacy) |
| Parent class | AbstractMap | Dictionary (legacy) |
| Iterator behavior | Fail-fast | Enumerator not fail-fast; Iterator fail-fast |
| Modern replacement | Use directly for single-threaded | Use ConcurrentHashMap instead |
Identifies synchronization and null-handling differences correctly. Mentions that Hashtable is legacy.
Covers synchronization, null handling, legacy status. Explains why ConcurrentHashMap replaces Hashtable. Mentions Collections.synchronizedMap as an alternative. Discusses iteration behavior.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment