HashMap vs Hashtable in Java
In Java, both HashMap and Hashtable are implementations of the Map interface and are
used to store key-value pairs. However, there are significant differences between them in
terms of synchronization, performance, null handling, and usage.
1. Basic Overview
HashMap:
- Introduced in Java 1.2 (part of Collections framework).
- Non-synchronized and faster.
- Allows one null key and multiple null values.
Hashtable:
- Introduced in Java 1.0 (legacy class).
- Synchronized (thread-safe).
- Does not allow null keys or values.
2. Key Differences Between HashMap and Hashtable
Feature HashMap Hashtable
Thread Safety Not synchronized (not Synchronized (thread-safe)
thread-safe)
Null Keys Allows one null key Does not allow any null key
Null Values Allows multiple null values Does not allow any null
value
Performance Faster because it is non- Slower due to
synchronized synchronization overhead
Iteration Uses Iterator, fail-fast Uses Enumerator, not fail-
fast
Legacy Part of Java Collections Legacy class, part of earlier
Framework versions
Preferred Use When thread safety is not When multiple threads
required access the map
concurrently
Skillio, Pune +91-9970806160 | +91-8484831616
3. Example: HashMap
import [Link];
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
// Adding entries
[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");
[Link](null, "Null Key Example"); // Allows null key
[Link](4, null); // Allows null values
// Iterating over map
for (Integer key : [Link]()) {
[Link]("Key: " + key + ", Value: " + [Link](key));
}
}
}
4. Example: Hashtable
import [Link];
public class HashtableExample {
public static void main(String[] args) {
Skillio, Pune +91-9970806160 | +91-8484831616
Hashtable<Integer, String> table = new Hashtable<>();
// Adding entries
[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");
// The following will throw NullPointerException
// [Link](null, "Null Key Not Allowed");
// [Link](4, null);
// Iterating over table
for (Integer key : [Link]()) {
[Link]("Key: " + key + ", Value: " + [Link](key));
}
}
}
5. Performance Consideration
- HashMap should be used in single-threaded applications or when thread safety is managed
externally (e.g., using [Link]() or ConcurrentHashMap).
- Hashtable is rarely used in new applications. Instead, developers use ConcurrentHashMap
for thread-safe operations with better performance.
6. When to Use What?
Use HashMap when:
- You don’t require thread-safety.
- You need better performance.
- You want to allow null keys or values.
Use Hashtable when:
- You are working with legacy code.
- You need thread-safe implementation but can’t use ConcurrentHashMap.
7. Recommendation
For new applications:
- Prefer HashMap for general use.
- Prefer ConcurrentHashMap for concurrent environments.
- Avoid Hashtable, as it is considered legacy and slower.
Skillio, Pune +91-9970806160 | +91-8484831616