JAVA

JAVA – Differences between HashMap and Hashtable in java

Java Articles, Errors and Fixes
Java Articles, Errors and Fixes

Java HashMap class

  • Java HashMap class implements the map interface by using a hashtable.
  • It inherits AbstractMap class and implements Map interface.

A HashMap contains values based on the key. Java HashMap class

  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.

Java Hashtable class

Java Hashtable class implements a hashtable, which maps keys to values. It inherits class and implements the Map interface. Java Hashtable class are:

  • A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.

Similarities Between HashMap and Hashtable

1. Insertion Order :   Both HashMap and Hashtable  does not guarantee that  the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.

2. Map interface :   Both HashMap and Hashtable implements Map interface .

3. Put and get method :  Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.

4. Internal working :  Both HashMap and Hashtable works on the Principle of Hashing .

  • The HashMapclass is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMapallows null values as key and value whereas Hashtable doesn’t allow nulls).
  • HashMapdoes not guarantee that the order of the map will remain constant over time.
READ  JAVA programming - Check if a graph is strongly connected

Difference between HashMap and HashTable / HashMap vs HashTable

  1. Synchronization or Thread Safe :  HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
  2. Null keys and null values :  Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
  3.  Iterating the values:  Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.
  4. Fail-fast iterator  :
    • The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.
    • According to Oracle Docs,  if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator’s own remove method , then the iterator will throw ConcurrentModification Exception.
    • Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) .
    • Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.
  5. Performance :
    • Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized .
    • Unsynchronized objects are often much better in performance in compare to synchronized  object like Hashtable in single threaded environment.
  6. Superclass and Legacy :
    • Hashtable is a subclass of Dictionary class which is now in Jdk 1.7 ,so ,it is not used anymore.
    • It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).
    • HashMap is the subclass of the AbstractMap class.
    • Although Hashtable and HashMap has different superclasses but they both are implementations of the “Map”  abstract data type.
READ  Java Algorithm - Infix to Postfix Conversion using Stack

Example of HashMap  and HashTable

java code
mport java.util.Hashtable;

public class HashMapHashtableExample
 {
    public static void main(String[] args)
 { 
        Hashtable<String,String> hashtableobj = new    Hashtable<String, String>();
        hashtableobj.put("wikitechy", "tutorial");
        hashtableobj.put("View", "website");
        System.out.println("Hashtable object output :"+ hashtableobj);
 
        HashMap hashmapobj = new HashMap();
        hashmapobj.put("wikitechy", "tutorial");  
        hashmapobj.put("View", "website"); 
        System.out.println("HashMap object output :"+hashmapobj);   
 
 }
}

Output :  Hashtable object output :{View=website, wikitechy=tutorial}
HashMap object output :{wikitechy=tutorial, View=website}

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 outdated in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded  application prefer ConcurrentHashMap instead of Hashtable.

 

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment