The short answer

HashMap and Hashtable both store key-value pairs using hashing, but HashMap is not synchronised, allows one null key and null values, and is faster. Hashtable is synchronised (thread-safe), allows no null key or value, and is a legacy class. In short, use HashMap by default, and for thread safety prefer ConcurrentHashMap over the old Hashtable.

HashMap vs Hashtable is a classic Java comparison, since both store key-value pairs through hashing. Both appear in every Java and interview syllabus. Developers often blur which one is thread-safe and which one accepts a null key.

The core split is synchronisation and null handling. Is the class locked for threads, and can a key be null? HashMap says no to both, while Hashtable says yes then no. This guide defines each class, shows how hashing works, compares them in detail, and explains when to use which.

If you are still mapping out Java collections, it also helps to know the difference between HashMap and HashSet.

Two panels comparing HashMap as not synchronized, allowing a null key and faster, against Hashtable as synchronized, allowing no null and legacy
HashMap is unsynchronised and allows a null key; Hashtable is synchronised and allows none.

What is a HashMap?

A HashMap is a Java class that stores data as key-value pairs using hashing. A hash function maps each key to a bucket in an internal array, so lookups run in roughly constant time. It belongs to the Java Collections Framework, and it is the everyday map for general use.

Crucially, HashMap is not synchronised, so it is fast in a single thread but unsafe if threads share it. It also allows one null key and any number of null values. When two keys hash to the same bucket, HashMap handles the collision with chaining, and it resizes automatically as it fills.

Advantages of HashMap:

  • Fast retrieval, since there is no synchronisation overhead.
  • Allows one null key and null values, which adds flexibility.
  • Dynamic sizing, so it adapts to a varying amount of data.
  • Part of the modern Collections Framework, with a fail-fast iterator.

Disadvantages of HashMap:

  • Not thread-safe, so shared access needs external synchronisation.
  • Frequent resizing can add some memory and time cost.

What is a Hashtable?

A Hashtable also stores key-value pairs through hashing, so on the surface it looks like a HashMap. The difference is that Hashtable is synchronised: every method is locked, which makes it thread-safe for concurrent access. It is one of the oldest Java classes, dating back to JDK 1.0.

Because of that locking, Hashtable runs slower than HashMap. It also allows no null key and no null value, so putting a null throws a NullPointerException. Today it is considered legacy, and modern code prefers other options for thread safety.

Advantages of Hashtable:

  • Thread-safe, since all its methods are synchronised.
  • Safe for many threads sharing one table without extra code.
  • Simple, well-understood behaviour from long use.

Disadvantages of Hashtable:

  • Slower than HashMap, due to whole-table locking.
  • Rejects null keys and null values, throwing an exception.
  • Legacy design, largely replaced by ConcurrentHashMap.

HashMap vs Hashtable: Comparison Table

Grid comparing HashMap and Hashtable on synchronized no/yes, null key yes/no, iterator fail-fast/enumeration, and speed faster/slower
HashMap vs Hashtable at a glance: synchronization, null keys, iteration, and speed.
AspectHashMapHashtable
SynchronisationNot synchronisedSynchronised (thread-safe)
Null key / valuesOne null key and null values allowedNo null key or value (throws NullPointerException)
Performance (single thread)Faster, no locking overheadSlower due to synchronisation
Performance (multithread)Needs external synchronisationBuilt-in synchronisation
IterationIterator, which is fail-fastIterator and legacy Enumeration
Introduced inJDK 1.2 (Collections Framework)JDK 1.0 (legacy)
Default capacity16, load factor 0.7511, load factor 0.75
SizingResizes dynamically as it fillsAlso resizes dynamically as it fills
Collision handlingChaining (and treeify large buckets)Chaining
Concurrency controlExternal, or use ConcurrentHashMapWhole-table lock on each method
Preferred useSingle-threaded, general purposeRarely; kept for legacy code
Scenario suitabilityWhere synchronisation is not criticalWhere simple thread safety is required
Modern usageCommon in modern JavaLegacy; alternatives available
RecommendationDefault map choicePrefer ConcurrentHashMap instead

How Hashing Works (Code)

Diagram of a key passing through a hash function into an array of buckets, with a collision at one bucket resolved by a chain of linked entries
A hash function maps each key to a bucket; collisions form a chain.

Both classes share the same core idea: a hash function turns a key into a bucket index, so a lookup goes almost straight to the value. The clearest way to see their difference is the null-key rule.

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

public class MapDemo {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("a", 1);
        map.put(null, 0);          // HashMap allows one null key
        System.out.println(map.get("a"));   // 1

        Hashtable<String, Integer> table = new Hashtable<>();
        table.put("a", 1);         // fine
        // table.put(null, 0);     // Hashtable would throw NullPointerException
        System.out.println(table.get("a")); // 1
    }
}

Notice the one commented line. A HashMap accepts null as a key, while a Hashtable rejects it at runtime. So that single behaviour often decides which class a codebase uses.

The Modern Choice: ConcurrentHashMap

Hashtable makes a whole map thread-safe, yet it does so with one coarse lock, so only one thread works at a time. That is why modern Java rarely uses it. Instead, when threads must share a map, developers reach for ConcurrentHashMap.

ConcurrentHashMap locks only small parts of the map, so many threads can read and write at once. As a result, it scales far better than Hashtable under load. So the practical rule is simple: use HashMap for single-threaded code, and ConcurrentHashMap for concurrent code, leaving Hashtable to old projects.

When to Use Which

You choose by asking whether threads share the map.

Use a HashMap for almost everything in single-threaded code. It is fast, it accepts a null key, and it is the modern default. So unless you have a concurrency need, reach for HashMap first.

Use a Hashtable only when you maintain legacy code that already depends on it. For new thread-safe needs, prefer ConcurrentHashMap, since it gives safety without the coarse lock. Therefore Hashtable is a compatibility choice rather than a fresh one.

Interview Questions

HashMap allows exactly one null key and any number of null values. Hashtable allows neither, so putting a null key or value throws a NullPointerException. That contrast is one of the most common interview answers for the pair.

Every Hashtable method is synchronised, so it takes a lock even in a single thread. HashMap skips that locking, so it avoids the overhead entirely. Therefore HashMap runs faster whenever thread safety is not needed.

HashMap is traversed with an Iterator, which is fail-fast and throws if the map changes during iteration. Hashtable also supports the older Enumeration, which is not fail-fast. So the Iterator gives safer, more modern traversal.

No, new code should use ConcurrentHashMap instead. Hashtable locks the whole map, so it scales poorly, while ConcurrentHashMap locks only small parts and handles many threads well. So Hashtable stays only for legacy compatibility.

Frequently Asked Questions

HashMap is generally faster in single-threaded scenarios, because it has no synchronisation overhead. Hashtable locks every method, so it is slower. However, in a multithreaded setting Hashtable is at least safe, though ConcurrentHashMap is faster and safe.

They share a similar key-value API, yet they differ in synchronisation and null handling, so they are not always interchangeable. A Hashtable will reject a null key that a HashMap accepts. So you must weigh thread safety and null use before swapping one for the other.

Both use chaining, so entries that hash to the same bucket form a linked chain. Modern HashMap even converts a very long chain into a balanced tree for speed. Hashtable keeps the simpler chain, and its synchronisation guards updates during concurrent access.

Mostly only in legacy code that already relies on it. Hashtable does give simple built-in thread safety, so it can suit an old multithreaded module. For anything new, though, ConcurrentHashMap is the better thread-safe choice.

Resizing does cost some time and memory, since the map rehashes its entries when it grows past the load factor. You can reduce this by setting a sensible initial capacity. So for large, known data sizes, presizing the HashMap helps performance.

Yes, ConcurrentHashMap is the modern replacement for thread-safe maps, and plain HashMap covers single-threaded use. Both outperform Hashtable in their intended setting. So Hashtable is now largely legacy, kept mainly for backward compatibility.

Wrapping Up

HashMap and Hashtable both hash key-value pairs, yet they sit at different trade-off points. HashMap is fast, unsynchronised, and allows a null key, while Hashtable is synchronised, rejects null, and is a legacy class.

Remember the simple rule: use HashMap for single-threaded code, and reach for ConcurrentHashMap, not Hashtable, when threads share the map. Knowing the synchronisation and null differences answers most exam and interview questions on the two.

Related reading on DiffStudy:


Whatsapp-color Created with Sketch.

By Arun Kumar

Full Stack Developer with a BE in Computer Science, working with React, Next.js, Node.js, MongoDB, and AI/ML tools. Founder of DiffStudy — built to help CS students ace GATE and university exams, and keep developers up to date across AI, cloud, system design, web development, and every field of computer science. Every article is written from real hands-on experience, not just theory.

Leave a Reply

Your email address will not be published. Required fields are marked *


You cannot copy content of this page