HashMap vs HashTable
- HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
- Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
- Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator’s own remove method , then the iterator will throw ConcurrentModification Exception.
Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.
- Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.
Similarities Between HashMap and Hashtable
- Insertion Order :Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
- Map interface :Both HashMap and Hashtable implements Map interface .
- Put and get method :Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
- Internal working :Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .
When to use HashMap and Hashtable?
Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .
Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.