What are the differences between a HashMap and a Hashtable in Java?

There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. 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.

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

  1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code.
  2. HashMap allows one null key and multiple null values.
  3. HashMap is a new class introduced in JDK 1.2.
  4. HashMap is fast.
  5. We can make the HashMap as synchronized by calling this code
    Map m = Collections.synchronizedMap(HashMap);
  6. HashMap is traversed by Iterator.
  7. Iterator in HashMap is fail-fast.
  8. HashMap inherits AbstractMap class.

Hashtable

  1. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  2. Hashtable doesn’t allow null key or value.
  3. Hashtable is a legacy class.
  4. Hashtable is slow.
  5. Hashtable is internally synchronized and can’t be unsynchronized.
  6. Hashtable is traversed by Enumerator and Iterator.
  7. Enumerator in Hashtable is not fail-fast.
  8. 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.

  1. The 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 nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the 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:

  1. 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.
  2. 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 calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
  3. 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 HashMapLinkedHashMap, 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:

HashMapHashtable
SynchronizedNoYes
Thread-SafeNoYes
Null Keys and Null valuesOne null key ,Any null valuesNot permit null keys and values
Iterator typeFail fast iteratorFail safe iterator
PerformanceFastSlow in comparison
Superclass and LegacyAbstractMap , NoDictionary , Yes

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →