HashMap and HashTable are both key-value based data structures in Java, but they differ in synchronization, performance, and flexibility.
Hashtable is synchronized, which means it allows only one thread to access it at a time — making it thread-safe but slower in performance. On the other hand, HashMap is not synchronized, so multiple threads can access it simultaneously, making it faster but not thread-safe by default.
Both HashMap and Hashtable provide similar methods such as put(), get(), and remove() to add, retrieve, and delete elements.
🧾 Comparison Table
| Feature | HashMap | Hashtable |
|---|---|---|
| Package | java.util | java.util |
| Synchronization | Not synchronized | Synchronized |
| Thread Safety | Not thread-safe | Thread-safe |
| Performance | Faster (no synchronization overhead) | Slower (synchronized) |
| Null Keys/Values | Allows one null key and multiple null values | Does not allow any null keys or values |
| Iteration Order | Unordered | Unordered |
| Introduced In | Java 1.2 (part of Collections Framework) | Java 1.0 (legacy class) |
| Legacy | Modern class | Legacy class (use discouraged) |
| Alternative for Thread Safety | Use Collections.synchronizedMap() or ConcurrentHashMap | Already thread-safe |
💻 Example: HashMap vs Hashtable
import java.util.*;
public class HashMapVsHashtableExample {
public static void main(String[] args) {
// ----- HashMap Example -----
System.out.println("----- HashMap Example -----");
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Cherry");
hashMap.put(null, "Mango"); // ✅ Allows one null key
hashMap.put(4, null); // ✅ Allows null values
System.out.println("HashMap contents: " + hashMap);
// Accessing elements
System.out.println("Get value for key 2: " + hashMap.get(2));
hashMap.remove(3);
System.out.println("After removing key 3: " + hashMap);
// ----- Hashtable Example -----
System.out.println("\n----- Hashtable Example -----");
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(1, "Dog");
hashtable.put(2, "Cat");
hashtable.put(3, "Tiger");
// ❌ Hashtable does not allow null keys or values
try {
hashtable.put(null, "Lion"); // Throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Hashtable error: Null key not allowed!");
}
try {
hashtable.put(4, null); // Throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Hashtable error: Null value not allowed!");
}
System.out.println("Hashtable contents: " + hashtable);
// Accessing elements
System.out.println("Get value for key 2: " + hashtable.get(2));
hashtable.remove(3);
System.out.println("After removing key 3: " + hashtable);
}
}