What is the difference between HashMap and HashTable in Java?
Answer
The primary difference is thread safety. HashTable is a legacy class (since Java 1.0) where all methods are synchronized, making it thread-safe but slow due to the overhead of acquiring a lock on every operation. HashMap is not synchronized and therefore faster in single-threaded environments. HashMap allows one null key and multiple null values; HashTable does not allow any null keys or values. HashMap is part of the Collections Framework (implements Map); HashTable extends the old Dictionary class. For thread-safe maps, prefer ConcurrentHashMap over HashTable — it uses lock striping for much better concurrency performance.
Previous
What is HashMap in Java and how does it work internally?
Next
What is the difference between HashMap and LinkedHashMap?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and LinkedHashMap?
- Intermediate What is the difference between HashSet and TreeSet?