There are several differences between HashMap
and Hashtable
in Java:
Hashtable
is synchronized, whereasHashMap
is not. This makesHashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.Hashtable
does not allownull
keys or values.HashMap
allows onenull
key and any number ofnull
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 theHashMap
for aLinkedHashMap
. This wouldn’t be as easy if you were usingHashtable
.
Since synchronization is not an issue for you, I’d recommend HashMap
. If synchronization becomes an issue, you may also look at ConcurrentHashMap
.
HashMap vs HashTable in Java:
There are many good answers already posted. I’m adding few new points and summarizing it.
HashMap
and Hashtable
both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
HashMap
is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code.HashMap
allows one null key and multiple null values.HashMap
is a new class introduced in JDK 1.2.HashMap
is fast.- We can make the
HashMap
as synchronized by calling this codeMap m = Collections.synchronizedMap(HashMap);
HashMap
is traversed by Iterator.- Iterator in
HashMap
is fail-fast. HashMap
inherits AbstractMap class.
Hashtable
Hashtable
is synchronized. It is thread-safe and can be shared with many threads.Hashtable
doesn’t allow null key or value.Hashtable
is a legacy class.Hashtable
is slow.Hashtable
is internally synchronized and can’t be unsynchronized.Hashtable
is traversed by Enumerator and Iterator.- Enumerator in
Hashtable
is not fail-fast. Hashtable
inherits Dictionary class.
Further explanations:
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
.
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 synchronized 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);
Answer #3:
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.
- The
HashMap
class is roughly equivalent toHashtable
, except that it is non synchronized and permits nulls. (HashMap
allows null values as key and value whereasHashtable
doesn’t allownull
s). HashMap
does not guarantee that the order of the map will remain constant over time.HashMap
is non synchronized whereasHashtable
is synchronized.- Iterator in the
HashMap
is fail-safe while the enumerator for theHashtable
is not and throwConcurrentModificationException
if any other Thread modifies the map structurally by adding or removing any element exceptIterator
‘s ownremove()
method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms:
- Synchronized means only one thread can modify a hash table at one point in 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 the lock to be released. - Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke the
set
method since it doesn’t modify the collection “structurally”. However, if prior to callingset
, the collection has been modified structurally,IllegalArgumentException
will be thrown. - Structurally modification means deleting or inserting element which could effectively change the structure of the map.
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
.

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.
Apart from the differences already mentioned, it should be noted that since Java 8, HashMap
dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is
O(log(n)) for HashMap
Vs O(n) in Hashtable
.
*The aforementioned improvement has not been applied to Hashtable
yet, but only to HashMap
, LinkedHashMap
, and ConcurrentHashMap
.
FYI, currently,
TREEIFY_THRESHOLD = 8
: if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.UNTREEIFY_THRESHOLD = 6
: when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.
Summarizing the differences between HashMap and HashTable:
HashMap | Hashtable | |
---|---|---|
Synchronized | No | Yes |
Thread-Safe | No | Yes |
Null Keys and Null values | One null key ,Any null values | Not permit null keys and values |
Iterator type | Fail fast iterator | Fail safe iterator |
Performance | Fast | Slow in comparison |
Superclass and Legacy | AbstractMap , No | Dictionary , Yes |
Hope you learned something from this post.
Follow Programming Articles for more!