Introduction:
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:
- java.util.Map Interface Implementation: Both implements java.util.Map interface and are used to store key-value pairs.
- Hashing algorithm: Both uses Hashing algorithm as an internal implementation.
Differences Between HashMap and HashTable:
Now let’s learn the differences:
- AbstractMap vs Dictionary: HashMap class inherits java.util.AbstractMap class whereas the HashTable class inherits from java.util.Dictionary.
- 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 application.java.util.ConcurrentHashMap helps us create a synchronized HashMap and is preferable over using a HashTable from Java 7 onwards. HashTable is now an obsolete class.
- 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.
- 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.
- 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.
Conclusion:
In this quick tutorial, we learned the major differences between a HashMap and a HashTable in Java.