Difference Between HashMap, HashSet, and Hashtable in Java
Introduction
Java provides multiple hash-based data structures in its Collections Framework.
HashMap, HashSet, and Hashtable are commonly used but serve different purposes.
Understanding their differences is crucial for writing efficient code and answering interview questions.
HashMap
HashMap stores key-value pairs. It allows one null key and multiple null values.
It is not synchronized, meaning it is faster but not thread-safe.
Map<Integer, String> map = new HashMap<>();
map.put(1, "Alice");
map.put(2, "Bob");
map.put(null, "Charlie"); // null key allowed
System.out.println(map);
HashSet
HashSet stores unique elements only. Internally, it uses a HashMap to store values as keys with a dummy object as value.
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // duplicate ignored
System.out.println(set);
Hashtable
Hashtable is a legacy class that also stores key-value pairs.
Unlike HashMap, it is synchronized, meaning it is thread-safe but slower.
It does not allow null keys or null values.
Map<Integer, String> table = new Hashtable<>();
table.put(1, "Alice");
table.put(2, "Bob");
// table.put(null, "Charlie"); // throws NullPointerException
System.out.println(table);
Comparison Table
| Aspect | HashMap | HashSet | Hashtable |
|---|---|---|---|
| Type | Key-Value pairs | Unique elements | Key-Value pairs |
| Null Handling | One null key, multiple null values | Allows one null element | No null keys or values |
| Synchronized | No | No | Yes |
| Performance | Faster (not thread-safe) | Faster (not thread-safe) | Slower (thread-safe) |
| Introduced | Java 1.2 | Java 1.2 | Java 1.0 (legacy) |
| Internal Implementation | Array of buckets + linked list/tree | Backed by HashMap | Array of buckets + linked list |
When to Use Each
- HashMap: When you need fast, non-thread-safe key-value storage with null support.
- HashSet: When you need to store unique elements without duplicates.
- Hashtable: When you need synchronized key-value storage (though
ConcurrentHashMapis preferred today).
Interview-Ready Notes
- HashMap vs Hashtable: HashMap is non-synchronized and allows nulls; Hashtable is synchronized and disallows nulls.
- HashSet vs HashMap: HashSet stores only values (unique), while HashMap stores key-value pairs.
- Best Practice: Use
HashMapfor general-purpose maps,HashSetfor uniqueness, andConcurrentHashMapinstead ofHashtablefor thread safety.
Conclusion
HashMap, HashSet, and Hashtable are all hash-based but serve different roles. HashMap is versatile and widely used, HashSet ensures uniqueness, and Hashtable is a legacy synchronized map. Understanding their differences helps you choose the right collection for your needs and confidently answer interview questions.