HashMap vs HashTable in Java

In this post, we will learn the difference between HashMap and HashTable in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between HashMap and HashTable in Java

Features HashMap HashTable
Synchronization Not synchronized (not thread-safe) Internally synchronized (thread-safe)
Null Elements Allows one null key and any number of null values Doesn't allow null keys and null values
Iterators Returns fail-fast iterators Returns fail-safe Enumerations
Class Extension Extends AbstractMap class Extends Dictionary class
Traversal Returns only iterator Returns both Iterator and Enumeration
Speed Fast Slow
Legacy Class Not a legacy class Is a legacy class
Preferred Use Preferred in single-threaded applications; for multi-threaded, wrap using Collections.synchronizedMap() Not preferred nowadays for multi-threaded applications; ConcurrentHashMap is a better option

Example with HashMap:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> hMap = new HashMap<>();

        // Add elements (key-value pairs)
        hMap.put(1, "apple");
        hMap.put(2, "banana");
        hMap.put(3, null);
        hMap.put(null, "cherry");

        // Display the HashMap
        System.out.println("HashMap:");
        for (Integer key : hMap.keySet()) {
            System.out.println(key + " => " + hMap.get(key));
        }
    }
}

Output:

HashMap:
null => cherry
1 => apple
2 => banana
3 => null

Example with HashTable:

import java.util.Hashtable;

public class HashTableExample {
    public static void main(String[] args) {
        // Create a HashTable
        Hashtable<Integer, String> hTable = new Hashtable<>();

        // Add elements (key-value pairs)
        hTable.put(1, "apple");
        hTable.put(2, "banana");
        hTable.put(3, "cherry");
        // hTable.put(null, "date"); // This will throw NullPointerException
        // hTable.put(4, null);      // This will also throw NullPointerException

        // Display the HashTable
        System.out.println("HashTable:");
        for (Integer key : hTable.keySet()) {
            System.out.println(key + " => " + hTable.get(key));
        }
    }
}

Output:

HashTable:
1 => apple
2 => banana
3 => cherry

Download Cheat Sheet:

Related Collections Interview QA

  1. map() vs flatMap() in Java
  2. Collections vs Streams
  3. ArrayList vs Vector
  4. Iterator vs ListIterator
  5. HashMap vs HashTable
  6. HashSet vs HashMap
  7. Array vs ArrayList
  8. Fail-Fast Iterators vs Fail-Safe Iterators
  9. HashMap vs ConcurrentHashMap
  10. LinkedList vs ArrayDeque
  11. LinkedList vs Array
  12. LinkedList vs Doubly LinkedList
  13. Enum vs EnumSet in Java
  14. HashMap vs. TreeMap in Java
  15. Synchronized Collections vs. Concurrent Collections

Comments