What is difference between HashMap and Hashtable
Last updated: September 2026 — refreshed with code examples, a comparison table, and interview Q&A.
HashMap vs Hashtable is one of the most-asked Java interview questions of all time — right up there with why String is immutable and ArrayList vs LinkedList. Sometimes the interviewer just wants the differences; sometimes it's a gateway into concurrency. This post covers both.
HashMap vs Hashtable: the differences
| Feature | HashMap | Hashtable |
|---|---|---|
| Synchronized | No — faster in single-threaded code | Yes — every method is synchronized |
| Null keys / values | One null key, any number of null values | No null keys or values (throws NullPointerException) |
| Iteration order | Unordered, but LinkedHashMap subclass preserves insertion order | Unordered, no ordered variant |
| Iterator behavior | Fail-fast — throws ConcurrentModificationException on structural change during iteration | Enumerator is not fail-fast |
| Default capacity | 16 | 11 |
| Since | Java 1.2 (Collections framework) | Java 1.0 (legacy) |
The differences in code
Null handling — the easiest way to get tripped up in an interview:
Map<String, String> hashMap = new HashMap<>();
hashMap.put(null, "allowed"); // fine
hashMap.put("key", null); // fine
Map<String, String> table = new Hashtable<>();
table.put(null, "boom"); // NullPointerException!
table.put("key", null); // NullPointerException!
Synchronization — Hashtable synchronizes every method, which is why HashMap wins on speed in single-threaded code. If you need a synchronized HashMap, wrap it instead of reaching for Hashtable:
Map<String, String> syncMap = Collections.synchronizedMap(new HashMap<>>());
What should you actually use in 2026?
Honest answer: almost never Hashtable. It's a legacy class from Java 1.0, kept around for backward compatibility. The modern rule is simple:
- Single thread →
HashMap - Multiple threads →
ConcurrentHashMap(finer-grained locking — far better throughput than Hashtable's method-level synchronization) - Insertion order matters → LinkedHashMap
- Sorted keys →
TreeMap
If an interviewer asks "why does Hashtable still exist?" — backward compatibility. That's the whole answer.
Interview rapid-fire
- Can two null keys exist in a HashMap? — No. One null key is allowed; a second
put(null, ...)overwrites the first. - Why is HashMap faster than Hashtable? — No synchronization overhead on any method.
- Is HashMap's fail-fast iterator guaranteed? — No — it's best-effort. Never write logic that depends on ConcurrentModificationException being thrown. (More on fail-fast vs fail-safe iterators.)
- What's the default load factor, and what happens when it's exceeded? — 0.75 for both; the table resizes (rehashes) when size exceeds capacity × load factor.
- HashMap or ConcurrentHashMap for a cache shared across threads? — ConcurrentHashMap. Always.
Comments
Post a Comment