This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Q: What is the difference between a HashMap and a Hashtable in Java?

What is the difference between a HashMap and a Hashtable in Java? Which is more efficient for single-threaded applications?

Answer 1:

There are some differences between HashMap and Hashtable in Java:

Hashtable supports concurrency, whereas HashMap does not. This HashMap is better for single-threaded applications because unsynchronized objects generally perform better than synchronized objects.

Hashtable does not allow NULL as a key or value. A HashMap allows one NULL key and any number of NULL values.

One of the subclasses of HashMap is LinkedHashMap, so if you want a predictable iteration order (insertion order by default), you can easily replace a HashMap with a LinkedHashMap. If you use Hashtable, this will not be easy for you.

Since synchronization is not an issue for you, it is recommended that you use HashMap. You can also look at ConcurrentHashMap if synchronization becomes a problem.

Answer 1: Next comment:

If you want to make a HashMap thread-safe, please use the Collections, synchronizedMap ().

Answer 2: Hashtable is considered legacy code. There is nothing you need to do with Hashtable that you can’t do with HashMap, so I don’t see any reason to use Hashtable with the new code.

Answer 3:

Notice that many of the answers indicate that the Hashtable has been synchronized. In practice, this will do you little good. Synchronization stops adding or removing two threads from the map at the same time in the accessor/changer method, but in the real world, you often need to do additional synchronization.

A very common idiom is “check before you drop” – that is, look up an item on a map and add it if it doesn’t already exist. Whether you use Hashtable or HashMap, this is not an atomic operation.

An equivalent synchronized HashMap can be obtained by:

Collections.synchronizedMap(myMap);
Copy the code

But to implement this logic correctly, you need to perform additional synchronization on the form:

synchronized(myMap) {
    if(! myMap.containsKey("tomato"))
        myMap.put("tomato"."red");
}
Copy the code

Even iterative Hashtable (or by the Collections. SynchronizedMap HashMap) is not thread-safe, unless you also prevent to modify the Map by additional synchronization.

Implementations of the ConcurrentMap interface, such as ConcurrentHashMap, address some of these issues by including thread-safe “check before you act” semantics, such as:

ConcurrentMap.putIfAbsent(key, value);
Copy the code