Here are the key differences between HashMap and Hashtable in Java:
1. Thread Safety & Synchronization
- Hashtable:
- Synchronized (thread-safe). Every method is synchronized, which ensures thread safety but introduces performance overhead.
- HashMap:
- Not synchronized (not thread-safe by default). Requires explicit synchronization (e.g.,
Collections.synchronizedMap
) for multi-threaded environments. - Better performance in single-threaded scenarios due to lack of synchronization.
- Not synchronized (not thread-safe by default). Requires explicit synchronization (e.g.,
2. Null Keys/Values
- Hashtable:
- Does NOT allow
null
keys or values. ThrowsNullPointerException
if used.
- Does NOT allow
- HashMap:
- Allows one
null
key and multiplenull
values.
- Allows one
3. Inheritance & Legacy Status
- Hashtable:
- Legacy class (since Java 1.0) extending the
Dictionary
class (now considered obsolete).
- Legacy class (since Java 1.0) extending the
- HashMap:
- Part of the modern Java Collections Framework (since Java 1.2) and implements the
Map
interface.
- Part of the modern Java Collections Framework (since Java 1.2) and implements the
4. Iteration
- Hashtable:
- Uses
Enumeration
to iterate over keys/values.
- Uses
- HashMap:
- Uses
Iterator
, which is fail-fast (throwsConcurrentModificationException
if modified during iteration).
- Uses
5. Performance
- Hashtable:
- Slower due to synchronization overhead.
- HashMap:
- Faster in single-threaded environments. For multi-threaded use, prefer
ConcurrentHashMap
over synchronizedHashMap
.
- Faster in single-threaded environments. For multi-threaded use, prefer
6. Recommended Usage
- Hashtable:
- Rarely used today. Largely replaced by
ConcurrentHashMap
or synchronized wrappers ofHashMap
.
- Rarely used today. Largely replaced by
- HashMap:
- Default choice for most scenarios. Use
ConcurrentHashMap
for thread-safe requirements.
- Default choice for most scenarios. Use
Example:
java
// Hashtable (no nulls allowed)
Hashtable<String, Integer> table = new Hashtable<>();
table.put("key", 100); // OK
table.put(null, 100); // Throws NullPointerException
// HashMap (allows null)
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 100); // OK
map.put(null, 200); // OK
Summary
Feature | Hashtable | HashMap |
---|---|---|
Thread Safety | Yes (synchronized) | No (requires external) |
Null Keys/Values | Disallowed | Allowed |
Legacy | Yes (Java 1.0) | No (Java 1.2+) |
Performance | Slower | Faster |
Iteration | Enumeration | Iterator (fail-fast) |
Prefer HashMap
unless legacy code requires Hashtable
, and use ConcurrentHashMap
for concurrent needs.