Homeβ€Ί Javaβ€Ί HashMap vs Hashtable in Java

HashMap vs Hashtable in Java

Where developers are forged. Β· Structured learning Β· Free forever.
πŸ“ Part of: Collections β†’ Topic 19 of 21
Understand the key differences between Java HashMap and Hashtable: synchronization, null keys, performance, and which to use in modern Java code.
πŸ§‘β€πŸ’» Beginner-friendly β€” no prior Java experience needed
In this tutorial, you'll learn:
  • Hashtable is a legacy class β€” don't use it in new code. Use HashMap for single-threaded access, ConcurrentHashMap for multi-threaded.
  • HashMap allows one null key and multiple null values. Hashtable and ConcurrentHashMap throw NullPointerException for null keys or values.
  • ConcurrentHashMap is the modern replacement for Hashtable β€” it's thread-safe and significantly faster because it only locks segments rather than the entire map.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚑ Quick Answer
HashMap and Hashtable both store key-value pairs. The difference is that Hashtable is thread-safe by default (every method is synchronised) while HashMap is not. That sounds like Hashtable should be preferred β€” but full synchronisation per method is actually too coarse for most concurrent use cases, and it costs performance even in single-threaded code. Modern Java has ConcurrentHashMap, which provides real thread-safety with much better throughput.

Hashtable predates the Java Collections Framework (it's been around since Java 1.0). It's a legacy class. If you're writing new code and thinking about thread-safety in a Map, the answer is ConcurrentHashMap, not Hashtable. HashMap for single-threaded code, ConcurrentHashMap for concurrent code. Hashtable for legacy code you're maintaining.

Key Differences with Code Examples

HashMapVsHashtableExample.java Β· JAVA
123456789101112131415161718192021222324252627282930313233343536
package io.thecodeforge.collections;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

public class HashMapVsHashtableExample {

    public static void main(String[] args) {
        // HashMap β€” not thread-safe, allows null key and null values
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(null, "null key allowed");
        hashMap.put("key1", null);       // null value allowed
        hashMap.put("key2", "value2");
        System.out.println(hashMap.get(null)); // null key allowed

        // Hashtable β€” thread-safe, does NOT allow null key or null value
        Hashtable<String, String> hashtable = new Hashtable<>();
        try {
            hashtable.put(null, "value");  // Throws NullPointerException
        } catch (NullPointerException e) {
            System.out.println("Hashtable: null key throws NPE");
        }
        hashtable.put("key1", "value1");  // Fine

        // ConcurrentHashMap β€” thread-safe, better performance than Hashtable
        // Does NOT allow null key or null value (same as Hashtable)
        ConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<>();
        concurrentMap.put("service", "PaymentService");
        // concurrentMap.put(null, "x"); // NullPointerException

        System.out.println("HashMap size: " + hashMap.size());
        System.out.println("Hashtable size: " + hashtable.size());
        System.out.println("ConcurrentHashMap size: " + concurrentMap.size());
    }
}
β–Ά Output
null key allowed
Hashtable: null key throws NPE
HashMap size: 3
Hashtable size: 1
ConcurrentHashMap size: 1
FeatureHashMapHashtableConcurrentHashMap
Thread-safe?NoYes (fully synchronised)Yes (segment-level)
Null keys allowed?Yes (one)NoNo
Null values allowed?YesNoNo
PerformanceFastSlow (full sync overhead)Fast (concurrent reads)
IntroducedJava 1.2Java 1.0 (legacy)Java 5
Recommended forSingle-threaded codeLegacy code onlyMulti-threaded code

🎯 Key Takeaways

  • Hashtable is a legacy class β€” don't use it in new code. Use HashMap for single-threaded access, ConcurrentHashMap for multi-threaded.
  • HashMap allows one null key and multiple null values. Hashtable and ConcurrentHashMap throw NullPointerException for null keys or values.
  • ConcurrentHashMap is the modern replacement for Hashtable β€” it's thread-safe and significantly faster because it only locks segments rather than the entire map.
  • For read-heavy concurrent workloads, ConcurrentHashMap excels β€” multiple threads can read simultaneously. Hashtable serialises all access.

⚠ Common Mistakes to Avoid

  • βœ•Using Hashtable for new multi-threaded code β€” use ConcurrentHashMap instead. Hashtable synchronises every method entirely, which creates a bottleneck. ConcurrentHashMap allows concurrent reads.
  • βœ•Expecting Hashtable to be safe for compound operations like check-then-put β€” even though methods are synchronised individually, two-method sequences are not atomic. Use ConcurrentHashMap's atomic methods like putIfAbsent().
  • βœ•Putting null keys into a map that might be iterated concurrently β€” both Hashtable and ConcurrentHashMap throw NPE for null keys. Only HashMap allows null keys.

Interview Questions on This Topic

  • QWhat is the difference between HashMap and Hashtable in Java?
  • QWhy is Hashtable not recommended for new concurrent Java code?
  • QWhat is the difference between Hashtable and ConcurrentHashMap?

Frequently Asked Questions

What is the difference between HashMap and Hashtable in Java?

HashMap is not synchronised (not thread-safe) and allows null keys and values. Hashtable is fully synchronised (every method is synchronised) and does not allow null keys or values. Hashtable is a legacy class from Java 1.0. For new multi-threaded code, use ConcurrentHashMap instead of Hashtable.

Is Hashtable deprecated in Java?

Hashtable is not formally deprecated but is considered a legacy class. The Java Collections Framework (introduced in Java 1.2) provides better alternatives: HashMap for non-concurrent use, ConcurrentHashMap for concurrent use. Modern code should not use Hashtable.

πŸ”₯
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousJava flatMap(): Flatten Streams and OptionalNext β†’Java Stream filter(): Filter Collections with Lambdas
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged