What are the differences between a HashMap
and a Hashtable
in Java?
Which is more efficient for non-threaded applications?
In general, you should use a HashMap. While both classes use keys to look up values, there are some important differences, including: A HashTable doesn't allow null keys or values; a HashMap does. A HashTable is synchronized to prevent multiple threads from accessing it at once; a HashMap isn't.
Hashtable and HashMap both implement Map , HashSet implements Set , and they all use hash codes for keys/objects contained in the sets to improve performance. Hashtable is a legacy class that almost always should be avoided in favor of HashMap .
When to use HashMap and Hashtable? HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications . We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 .
There are several differences between HashMap
and Hashtable
in Java:
Hashtable
is synchronized, whereas HashMap
is not. This makes HashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Hashtable
does not allow null
keys or values. HashMap
allows one null
key and any number of null
values.
One of HashMap's subclasses is LinkedHashMap
, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap
for a LinkedHashMap
. This wouldn't be as easy if you were using Hashtable
.
Since synchronization is not an issue for you, I'd recommend HashMap
. If synchronization becomes an issue, you may also look at ConcurrentHashMap
.
Note, that a lot of the answers state that Hashtable is synchronized. In practice this buys you very little. The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization.
A very common idiom is to "check then put" — i.e. look for an entry in the Map
, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable
or HashMap
.
An equivalently synchronised HashMap
can be obtained by:
Collections.synchronizedMap(myMap);
But to correctly implement this logic you need additional synchronisation of the form:
synchronized(myMap) {
if (!myMap.containsKey("tomato"))
myMap.put("tomato", "red");
}
Even iterating over a Hashtable
's entries (or a HashMap
obtained by Collections.synchronizedMap
) is not thread-safe unless you also guard the Map
against being modified through additional synchronization.
Implementations of the ConcurrentMap
interface (for example ConcurrentHashMap
) solve some of this by including thread safe check-then-act semantics such as:
ConcurrentMap.putIfAbsent(key, value);
Hashtable
is considered legacy code. There's nothing about Hashtable
that can't be done using HashMap
or derivations of HashMap
, so for new code, I don't see any justification for going back to Hashtable
.
This question is often asked in interviews to check whether the candidate understands the 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 the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With