What are the differences between a HashMap
and a Hashtable
in Java?
Which is more efficient for non-threaded applications?
Synchronization or Thread Safe :
Hash Map is not synchronized hence it is not thred safe and it cannot be shared between multiple threads without proper synchronized block whereas, Hashtable is synchronized and hence it is thread safe.
Null keys and null values :
HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.
Iterating the values:
Iterator in the HashMap is a fail-fast iterator 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.
Superclass and Legacy :
HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.
Performance :
As HashMap is not synchronized it is faster as compared to Hashtable.
Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection
HashMap
is emulated and therefore usable in GWT client code
whereas Hashtable
is not.
HashMap is a class used to store the element in key and value format.it is not thread safe. because it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.
The Hashtable class is synchronized, that is, it is designed to be used by applications that handle multiple or multithreaded process. Synchronized classes are less efficient in the classical case of an application to a process, so the Hashmap class is faster in general. The HashTable class does not accept the Null value, either for keys or for values, while the HashMap class allows a single key with Null and as many as null as possible.
ConcurrentMap
is not necessary here, as the Question says “non-threaded applications” meaning threading/concurrency is not an issue.HashTable
has traditionally been only chosen because of its partial threading protection. But that's been obviated byConcurrentHashMap
, so it's generally regarded as retired. It's generally recommended to choose betweenHashMap
orConcurrentHashMap
." And I believe that to be a sensible comment, if it's what she meant.