Site icon TestingDocs.com

Difference between HashMap and HashTable?

Introduction

Let’s look at some of the differences between HashMap and Hashtable in this tutorial. Hashtable is obsolete and we can replace implementations with some derivate of HashMap extensions. Though we talk about the differences in the section both the classes implement the same interfaces Map, Cloneable, and Serializable.

HashMap

HashMap is not thread-safe and not synchronized. We cannot use HashMap in multi-threaded applications.

Hapmap allows one null key and null values.

HashMap is faster and uses less memory.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapDemo {
  
  public static void main(String[] args) {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put(null,"Not defined");
    map.put("US","Washington DC");
    map.put("India","New Delhi");
    map.put("France","Paris");
    map.put("XYZ",null);
    traverse(map);
  }
  
  public static void traverse(HashMap<String,String> map) {
     Iterator itr = map.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry kvPair = (Map.Entry)itr.next();
            System.out.println(kvPair.getKey() + " = " + kvPair.getValue());
        }		
  }
}

HashTable

Hashtable is thread-safe and is synchronized.

Hashtable does not allow null keys and values.

Hashtable is an obsolete class and not used now. We can replace it with ConcurrentHashMap implementation in multi-threaded environments.

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class HashTableDemo {

  public static void main(String[] args) {
    Hashtable<String,String> table = new Hashtable<String,String>();
    table.put(null,"Not defined");
    table.put("US","Washington");
    table.put("India","New Delhi");
    table.put("France","Paris");
  }
  public static void traverse(Hashtable<String,String> table) {
     Iterator itr = table.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry kvPair = (Map.Entry)itr.next();
            System.out.println(kvPair.getKey() + " = " + kvPair.getValue());
        }		
  }
}

 

Exit mobile version