Hashtable Vs HashMap

Posted on Updated on

An interesting topic in collection framework is HashTable vs HashMap. Interviewers would love to ask questions on Hashtable. The basic difference every java programmer knows is Hashtable is synchronized while it’s not same with HashMap. There are some other differences between Hashtable and HashMap along with some common functionality as well, which we will be discussing in here.

Differences between HashMap and Hashtable.

HashMap Hashtable
HashMap is not synchronized, we can't use HashMap in multi-threading application without using proper syncronized code. Hashtable is synchronized, so we can use Hashtable in multithreaded environment.
HashMap can be synchronized by using method of Collections class as Collections.synchronizedMap(hashMap); HashTable is internally synchronized, so we can't unsynchronized it.
HashMap allows one null key and multiple null values. HashTable doesn't allow any null key or value.
HashMap inherits AbstractMap. HashTable inherits Dictionary class.
HashMap requires less memory compared to Hashtable while creating an object. Hashtable requires more memory compared to HashMap while creating an object.
Performance of HashMap is better compared to Hashtable as it requires less memory and runs faster. Performance of Hashtable as compared to HashMap is not good.
Iterator is used to traverse Hashmap. Iterator as well as Enumerator can used to traverse Hashtable.
HashMap is a new class introduced in JAVA 1.2 Hashtable is a legacy class.
Iterator in Hashmap is fail-fast. Enumerator in Hashtable is not fail-fast.

Similarities between HashMap and Hashtable.

  1. Both HashMap and Hashtable use principle of hashing to store key-value pair.
  2. Both HashMap and Hashtable don’t maintain insertion order.
  3. Both classes implements Map interface.
  4. Time required to perform put and get operation in both classes are same.

Uses of HashMap and Hashtable.

HashMap : When we are creating single threaded applications it is recommended to use HashMap because performance of HashMap is better as compared to Hashtable. Also, HashMap requires less space than Hashtable.

Hashtable : In multithreaded application, we can use Hashtable as it is internally synchronized. But in some scenarios it is recommended to use ConcurrentHashMap as it has some advantages over Hashtable in multithreaded environment. We will discuss advantages of ConcurrentHashMap in different blog.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.