Difference between HashTable and HashMap in Java


Following are the notable differences between HashTable and HashMap classes in Java.

 HashTableHashMap
SynchronizedHashTable is synchronized.HashMap is not synchronized.
Thread SafeHashTable is thread safe.HashMap is not thread safe.
Null objectsHashTable does not allows null keys or null values.HashMap allows one null key and multiple null values.
PerformanceHashTable is faster.HashMap is slower than HashTable.
Since Java Version1.21.5

Example

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Tester {
   public static void main(String args[]) {

      Map<String, String> map = new HashMap<String, String>();

      map.put("1", "One");
      map.put("2", "Two");
      map.put("3", "Three");
      map.put("5", "Five");
      map.put("6", "Six");

      System.out.println("HashMap: " + map);

      Map<String, String> map1 = new Hashtable<String, String>();
   
      map1.put("1", "One");
      map1.put("2", "Two");
      map1.put("3", "Three");
      map1.put("5", "Five");
      map1.put("6", "Six");

      System.out.println("HashTable: " + map1);
   }
}

Output

HashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six}
HashTable: {6 = Six, 5 = Five, 3 = Three, 2 = Two, 1 = One}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 21-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements