Difference between HashMap and HashTable? Can we make hashmap synchronized? HashTable vs HashMap?
November 26, 2011 Leave a comment
This question often asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.
- The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
- HashMap does not guarantee that the order of the map will remain constant over time.
- HashMap is non synchronized whereas Hashtable is synchronized.
- Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
- Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
- Structurally modification means deleting or inserting element which could effectively change the structure of map.
HashMap can be synchronized byMap m = Collections.synchronizeMap(hashMap);
- hashtable extends Dictionary interface which is quite old while hashmap extends Map interface.
- hashtalbe doesn’t have counterpart like ConcurrentHashMap.
- another important difference between hashtable and hashmap is , hashtable is less secure than hashmap because of Enumeration it uses. while hashmap uses iterator which prevents Concurrent Modification of HashMap, which is not possible in case of hashtable.
- stay out of hashtable use hashmap instead.