Difference between HashMap and Hashtable in Java
In this post, we will compare and contrast HashMap and Hashtable in Java, and explain their advantages and disadvantages.
A hash table is a data structure that maps keys to values using a hash function. It can allows fast and easy insertion, retrieval, and deletion of key-value pairs. Two of the most widely used types of hash tables in Java are HashMap and Hashtable, which both implement the Map interface.
1. Overview of HashMap in Java
HashMap is a class that implements the Map interface and uses a hash table as its underlying data structure to store key-value pairs. A key is an object that identifies a value, and a value is an object that contains some data. In HashMap, each key must be unique; however, duplicate values are allowed. The keys and values can be of any type. A HashMap offers many benefits:
HashMapallows fast access to elements by using the hash code of the keys. It uses an array of buckets to store the keys, where each bucket has a unique index calculated by applying a hash function to the key. When we insert or retrieve an element from theHashMap, we use the key to calculate the hash code and find the index of the bucket where the element is stored.HashMapdoes not maintain any order of the elements in the map, unlike some other types of maps such as TreeMap or LinkedHashMap. This means that the elements in aHashMapare stored in a random order according to their hash codes.HashMapallows null keys and null values in the map, unlike some other types of maps such as Hashtable or ConcurrentHashMap. This means that we can insert, retrieve, or remove null values from aHashMapwithout any problem.HashMapprovides additional methods to manipulate the map, such asput(),get(),remove(),containsKey(),containsValue(),size(),clear(), etc. These methods allow us to add, update, delete, or check elements in the map.
Let’s see an example of how to create and use a HashMap in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.HashMap; import java.util.Map; class Main { public static void main(String[] args) { // Create a HashMap object Map<String, Integer> map = new HashMap<>(); // Add some key-value pairs to the map map.put("Aaron", 10); map.put("Bella", 20); map.put("Casey", 30); // Print the map System.out.println("HashMap: " + map); // {Bella=20, Aaron=10, Casey=30} // Get the value associated with a key System.out.println("Value for Bella: " + map.get("Bella")); // 20 // Remove a key-value pair from the map map.remove("Aaron"); // Print the updated map System.out.println("HashMap: " + map); // {Bella=20, Casey=30} // Check if a key exists in the map System.out.println("Contains Bella: " + map.containsKey("Bella")); // true // Check if a value exists in the map System.out.println("Contains 10: " + map.containsValue(10)); // false } } |
2. Overview of Hashtable in Java
Hashtable is a class that implements the Map interface and uses a hash table as its underlying data structure to store key-value pairs. In a Hashtable, keys and values can be of any type where each key must be unique but duplicate values are allowed. It has some limitations:
Hashtableis synchronized, which means that it is thread-safe and can be shared among multiple threads. However, this also means that it has a performance penalty due to locking overhead. If thread-safety is not required, it is better to useHashMapinstead.Hashtabledoes not allow null keys or null values in the map, unlikeHashMap. This means that we cannot insert, retrieve, or remove null values from aHashtablewithout throwing an exception.Hashtabledoes not maintain any order of the elements in the map, unlike some other types of maps such asTreeMaporLinkedHashMap. This means that the elements in aHashtableare stored in a random order according to their hash codes.Hashtableprovides the same methods asHashMapto manipulate the map, such asput(),get(),remove(),containsKey(),containsValue(),size(),clear(), etc. However, it also provides some legacy methods that are not recommended to use, such as keys(), elements(), contains(), etc.
Let’s see an example of how to create and use a Hashtable in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Hashtable; import java.util.Map; class Main { public static void main(String[] args) { // Create a Hashtable object Map<String, Integer> map = new Hashtable<>(); // Add some key-value pairs to the map map.put("Aaron", 10); map.put("Bella", 20); map.put("Casey", 30); // Print the map System.out.println("Hashtable: " + map); // {Bella=20, Casey=30, Aaron=10} // Get the value associated with a key System.out.println("Value for Bella: " + map.get("Bella")); // 20 // Remove a key-value pair from the map map.remove("Aaron"); // Print the updated map System.out.println("Hashtable: " + map); // {Bella=20, Casey=30} // Check if a key exists in the map System.out.println("Contains Bella: " + map.containsKey("Bella")); // true // Check if a value exists in the map System.out.println("Contains 10: " + map.containsValue(10)); // false // Try to add a null key or value to the map map.put(null, 40); // NullPointerException map.put("David", null); // NullPointerException } } |
3. Difference between HashMap and Hashtable in Java
The functionality of HashMap and Hashtable are similar. They both use hashing to store and retrieve key-value pairs quickly. However, they also have some differences and trade-offs that we must understand. Here are some of them:
HashMapis a non-synchronized class, which means that it is not thread-safe and cannot be shared among multiple threads without proper synchronization code.Hashtableis a synchronized class, which means that it is thread-safe and can be shared among multiple threads.HashMapallows null keys and null values in the map, whereasHashtabledoes not allow any null key or value. If we try to insert or access a null value in aHashtable, it will throw aNullPointerException.HashMapis faster thanHashtable, as it does not have any locking overhead. However,HashMapmay not be suitable for multithreaded applications, as it may cause data inconsistency or concurrency issues.HashMapdoes not provide any legacy methods that are deprecated or not recommended to use, whereasHashtableprovides some legacy methods such askeys(),elements(),contains(), etc.Hashtableis a legacy class and should not be used if the thread-safe implementation is not required. Javadoc recommends usingConcurrentHashMapin place ofHashtablefor thread-safe highly concurrent implementation andHashMapclass otherwise.- The iterator returned by the
HashMapandHashtableclass is fail-fast. That meansConcurrentModificationExceptionwill be thrown if the map is structurally modified after the iterator is created without using the iterator’sremove()method.Hashtableis also traversed byEnumerator, which is not fail-fast. The results are undefined if theHashtableis structurally modified after the enumeration is created.
4. What to use and when?
As we have seen, HashMap and Hashtable are both useful classes to store and retrieve key-value pairs quickly using hashing. Here are some general recommendations on how to choose between them:
- If you need to store key-value pairs where each key is unique and can be used to access its associated value, we can use either
HashMaporHashtable. Both classes will provide the same functionality and performance for single-threaded applications. - If you need to store key-value pairs where each key is unique but also allow null keys or values, we should use
HashMap. This class will allow us to insert, retrieve, or remove null values from the map without any problem. - If you need to store key-value pairs where each key is unique but also support multithreading, we should use
Hashtable. This class will ensure that the map is synchronized and thread-safe and prevent any data inconsistency or concurrency issues. - If you need to store key-value pairs where each key is unique but also maintain the order of the elements according to their natural ordering or by a provided Comparator, we should use neither
HashMapnorHashtable, but useTreeMapinstead. This class will provide a sorted map implementation that uses a red-black tree as its underlying data structure.
That’s all about the differences between HashMap and Hashtable in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)