Difference Between HashMap And HashTable

Difference Between HashMap And HashTable

1. Synchronization or Thread Safe : This is the most important difference between two. 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. 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.

When to use HashMap and Hashtable?

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 .

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 multi threaded application prefer ConcurrentHashMap instead of Hashtable.

Example of HashMap and HashTable

public class HashMapHashtableExample {
    
    public static void main(String[] args) { 
 
        Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
        hashtableobj.put("Crazyfor ", "code");
        hashtableobj.put("Love", "the site");
        System.out.println("Hashtable object output :"+ hashtableobj);
 
        
        HashMap hashmapobj = new HashMap();
        hashmapobj.put("Crazyfor ", "code");  
        hashmapobj.put("Love", "the site"); 
        System.out.println("HashMap object output :"+hashmapobj);   
 
	}
}

Output : Hashtable object output :{Love=the site, Crazyfor =code}
HashMap object output :{Crazyfor =code, Love=the site}

One Thought on “Difference Between HashMap And HashTable

  1. abhinav singh on October 17, 2016 at 9:12 pm said:

    “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.

    ” – All the legacy classes (introduced in 1.0V) uses enumerator to iterate the value. Stack class also uses the enumerator.)

Leave a Reply to abhinav singh Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation