Last Updated:

Difference Between Hashtable and HashMap in Java

Difference Between Hashtable and HashMap in Java

In the course of working with each of the classes, a significant difference in performance was found on sufficiently large amounts of data. Having learned more about the documentation and features of the work of each collection, I decided to write this article - a small squeeze of the information received for the opportunity to quickly refresh the knowledge in the future. The Hashtable collection, although "ancient", is still used on old projects. In addition, practice shows that this question is often asked in interviews.

Briefly about HashMap

HashMap implements the Map interface, which involves storing data as key-value pairs. HashMap is not synchronized and thread-safe. HashMap also allows storing keys and values, but does not allow duplicate keys. Keep in mind that for a null key, hashCode() is always zero.null

A small example of using HashMap:

Hashtable at a glance

Hashtable implements the Map interface, which stores key-value pairs. Hashtable is a synchronized and thread-safe collection. Hashtable is not allowed null keys and duplicate keys, as well as null values.

Example of using HashMap:

And now let's consider the difference between Hashtable and HashMap on the example of a convenient table:

Characteristic
Hashtable
HashMap
Flow safety
+
Synchronicity
+
Performance
Thread safety and synchronicity makes it slow
In a single-threaded environment, it is much faster than Hashtable. If you are not working with multithreading, HashMap is recommended
Key == null?
Must not
Allows null key and null value
Alternative
No alternative
You can use ConcurrentHashMap to work in a multithreaded environment

Pay attention. Synchonized means that only one thread can change one table at the same time. When a thread runs with a Hashtable, it is closed to other threads until one thread runs.

HashMap can be synchronized by calling the following method:

Now, to work in a multithreaded environment, they often try to use the newer and more convenient ConcurrentHashMap collection, but this is the topic of another article.

Such a short cheat sheet will help to quickly refresh your memory important moments when working with Hastable and HashMap.

Follow the updates of the section Working with Collections and subscribe to new articles!