Difference between HashMap and HashTable in Java

Following are the major differences between HashMap and HashTable.

HashMap HashTable
HashMap is not thread safe. HashTable is thread safe.
HashMap has good performance as it is not synchronized. HashTable is slow in performance as it is synchronized.
HashMap allows one null key and any number of null values in it. HashTabe does not allow any null keys and values in it.
HashMap values are iterated by iterator. Iterator in HashMap is fail-fast HashTable values are iterated by iterator and enumeration. Enumerator in Hashtable is not fail-fast.
HashMap is a new class introduced in JDK 1.2 Hashtable is a legacy class.

A sample Java program to demonstrate HashMap and HashTable

import java.util.*; 
import java.lang.*; 
import java.io.*; 
 
class Dummy 
{ 
    public static void main(String args[]) 
    { 
        //----------hashtable ------------------------- 
        Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>(); 
        hashTable.put(101,"sachin"); 
        hashTable.put(101,"ganguly"); 
        hashTable.put(102,"kohli"); 
        hashTable.put(103,"pandya"); 
        System.out.println("-------------Hash table--------------"); 
        for (Map.Entry m:hashTable.entrySet()) { 
            System.out.println(m.getKey()+" "+m.getValue()); 
        } 
 
        //----------------hashmap-------------------------------- 
        HashMap<Integer,String> hashMap=new HashMap<Integer,String>(); 
        hashMap.put(100,"sachin"); 
        hashMap.put(101,"sachin");   
        hashMap.put(102,"kohli"); 
        hashMap.put(103,"pandya"); 
        System.out.println("-----------Hash map-----------"); 
        for (Map.Entry m:hashMap.entrySet()) { 
            System.out.println(m.getKey()+" "+m.getValue()); 
        } 
    } 
}

Hope you have enjoyed reading Difference between HashMap and HashTable in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.