What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
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.
Take a look at this chart. It provides comparisons between different data structures along with HashMap
and Hashtable
. The comparison is precise, clear and easy to understand.
Java Collection Matrix
Based on the info here, I'd recommend going with HashMap. I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.
Hashtable
is synchronized whereas HashMap
is not.HashMap
is fail-safe
while the enumerator for the Hashtable
isn't. If you change the map
while iterating, you'll know.HashMap
permits null values in it, while Hashtable
doesn't.Hashtable
is similar to the HashMap
and has a similar interface. It is recommended that you use HashMap
, unless you require support for legacy applications or you need synchronisation, as the Hashtables
methods are synchronised. So in your case as you are not multi-threading, HashMaps
are your best bet.
HashMap
and Hashtable
have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap
will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable
implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.
Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.