☕ Java Intermediate

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.