Below is the difference between Hashtable and HashMap:
- In terms of Null keys and Null values
- Hashtable does not allows null keys or values. If null keys or values tried to be inserted into the table then it throws java.lang.NullPointerException.
- HashMap allows multiple null values but single null key. Why single null keys? The reason is that if the key is same then the old value gets replaced with the new value.
- Iterating the Map
- Hashtable uses Enumerator to iterate through the table.
- HashMap uses iterator to iterate through the table.
- Thread safety
- Hashtable is synchronized and hence it is thread safe. It can be used in multithreading environment. Hashtable locks entire table to achieve synchronization. Better option for concurrency in map is ConcurrentHashMap as it does not lock entire table.
- HashMap is not synchronized so it is not thread safe and hence cannot be used in multithreaded environment. As it is not synchronized it is faster than Hashtable or ConcurrentHashMap. Also HashMap should be used in such environment which guarantees that the HashMap object will be not shared among different threads.
- Performance
- Hashtable is slow as it is synchronized.
- HashMap is faster than Hashtable as it is not synchronized and no overhead of been shared by different thread.
- Iterator in HashMap vs Enumerator in Hashtable
- Enumerator in Hashtable are not fail fast.
- Iterator in HashMap are fail fast. Means if the structure of Map is modified except the iterator’s own remove() method then it will throw ConcurrentModificationException.
Hashtable should not be used as it locks entire table. We can use ConcurrentHashMap as it does not lock entire table. It locks only the specific index in table which allows other thread to work with other index entries on map simultaneously.