What is the difference between HashMap and Hashtable?
HashMap is not thread safe, allows one null key and many null values, and is faster, so it is the default for single threaded code. Hashtable is thread safe because its methods are synchronised, does not allow null keys or values, and is slower and largely legacy. For thread safe needs today, prefer ConcurrentHashMap over Hashtable.
- HashMap is not synchronised, allows one null key, and is faster in single threaded code.
- Hashtable is synchronised, allows no null keys or values, and is largely legacy.
- For thread safe maps today, prefer ConcurrentHashMap over Hashtable.
Quick comparison
- Thread safety: HashMap is not synchronised, Hashtable is.
- Nulls: HashMap allows a null key and null values, Hashtable allows neither.
- Speed: HashMap is faster because it is not synchronised.
- Status: Hashtable is legacy, use ConcurrentHashMap for thread safe maps.
Map<String,Integer> m = new HashMap<>();
m.put(null, 1); // allowed in HashMap, not in Hashtable
The modern answer beats the textbook one. Say use HashMap normally and ConcurrentHashMap when you need thread safety, and treat Hashtable as legacy. That shows you know current practice, not just history.
Frequently asked questions
Why is ConcurrentHashMap preferred over Hashtable?
It allows safe concurrent access with much better performance by locking only parts of the map instead of the whole map like Hashtable does.
Can HashMap have null keys?
Yes, HashMap allows one null key and multiple null values, while Hashtable allows none.
Common follow up questions
Related interview questions
Want the full Java guide?
Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Java guide All Java questions