We will also see When to use hashmap and when to use a hashtable. Although both classes implement the Map in java there are some key differences in both of the classes. Now let’s see the difference between HashMap and Hashtable.
Difference in HashTable and HashMap
1. Synchronization or Thread Safe : This is the most important difference between Hashmap and Hashtable. HashMap is non-synchronized and not thread safe. On the other hand, HashTable is thread safe and synchronized.
When to use HashMap? If your application does not require any multi-threading task, in other words, the hashmap is better for non-threading applications. HashTable should be used in multithreading applications.
2. Iterating the values : Hashmap object values are iterated by using the iterator. HashTable is the only class other than vector which uses the enumerator to iterate the values of the HashTable object.
3. Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable does not allow null keys and null values in the HashTable object.
4. Performance : Hashmap is much faster and uses less memory than Hashtable because HashMap is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object because these don’t need to lock the object for other threads and release the lock once thread execution completes.
Synchronized means only one Thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
Similarities in HashMap and Hashtable
1. Insertion Order : Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time.
2. Interface Implementation : Both HashMap and Hashtable implements Map interface.
3. Insertion and Retrieve Methods : Both HashMap and Hashtable provides constant time performance for put() and get() methods assuming that the objects are distributed uniformly across the bucket.
Products from Amazon.in
Price: INR 419.00Was: INR 899.00
Price: INR 399.00Was: INR 699.00
Price: Out of stock
When to use HashMap and Hashtable?
1. Single Threaded Application : HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi-Threaded Application : We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.
So this is all about hashtable and Hashmap, We have discussed the differences, similarities & uses. If you still have any concern, feel free to write us.