Core Java

HashMap vs HashTable In Java


Both HashMap and HashTable implements java.util.Map interface and are used to store key-value pairs but there are some important differences between them.

In this tutorial, we’ll cover the differences between HashMap and HashTable.

Similarities Between HashMap and HashTable:

Before we cover the differences, let’s look first at the similarities between a HashMap and a HashTable:

  1. java.util.Map Interface Implementation: Both implements java.util.Map interface and are used to store key-value pairs.
  2. Hashing algorithm: Both uses Hashing algorithm as an internal implementation.

Differences Between HashMap and HashTable:

Now let’s learn the differences:

  1. AbstractMap vs Dictionary: HashMap class inherits java.util.AbstractMap class whereas the HashTable class inherits from java.util.Dictionary.
  2. Thread-safety: The methods defined in a HashTable are synchronized and thread-safe. The implementation of HashMap is not thread-safe and we need to handle concurrency on our own when using it in a multi-threaded helps us create a synchronized HashMap and is preferable over using a HashTable from Java 7 onwards. HashTable is now an obsolete class.
  3. Performance: In a non-threaded application, HashMap will perform way better than HashTable. The methods in a HashTable adds an additional overhead of handling synchronization which can be avoided in a single threaded application.
  4. Inserting null key and values: HashMap allows inserting one null key and any number of null values. HashMap doesn’t allow having either a null key or a null value. To be able to store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode() method and equals() method. HashMap in Java was later released as an improvement over HashTable and handles null as a special case.
  5. Elements Traversal: We can use an Iterator to traverse over a HashMap. Both Iterator and Enumerator can be used for traversal in case of a HashTable.

Note that the Enumerator in a HashTable is not fail-fast. To learn about the differences between fail-fast and fail-safe, we suggest reading this tutorial.


In this quick tutorial, we learned the major differences between a HashMap and a HashTable in Java.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *