What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.
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 null
s).HashMap
does not guarantee that the order of the map will remain constant over time.HashMap
is non synchronized whereas Hashtable
is synchronized.HashMap
is fail-safe 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.Note on Some Important Terms:
Hashtable
will have to acquire a lock on the object while others will wait for lock to be released.set
method since it doesn't modify the collection "structurally". However, if prior to calling set
, the collection has been modified structurally, IllegalArgumentException
will be thrown.HashMap
can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
Map provides Collection views instead of direct support for iteration
via Enumeration objects. Collection views greatly enhance the
expressiveness of the interface, as discussed later in this section.
Map allows you to iterate over keys, values, or key-value pairs;
Hashtable
does not provide the third option. Map provides a safe way
to remove entries in the midst of iteration; Hashtable
did not.
Finally, Map fixes a minor deficiency in the Hashtable
interface.
Hashtable
has a method called contains, which returns true if the
Hashtable
contains a given value. Given its name, you'd expect this
method to return true if the Hashtable
contained a given key, because
the key is the primary access mechanism for a Hashtable
. The Map
interface eliminates this source of confusion by renaming the method
containsValue
. Also, this improves the interface's consistency —
containsValue
parallels containsKey
.
The Map Interface