Answer
HashMap vs Hashtable in Java
HashMap
Introduced in Java 1.2. Part of the Collections Framework. Not thread-safe but fast.
Java
HashMap<String, String> map = new HashMap<>();
// Allows ONE null key and multiple null values
map.put(null, "null key value");
map.put("key1", null);
map.put("key2", "value2");
System.out.println(map.get(null)); // "null key value"
System.out.println(map.get("key1")); // null
// Fast — no synchronization overhead
map.put("user", "Alice");
map.put("role", "SDET");
System.out.println(map.size()); // 4
Hashtable
Introduced in Java 1.0 (legacy). All methods are synchronized — thread-safe but slow.
Java
Hashtable<String, String> table = new Hashtable<>();
// Does NOT allow null key or null value
// table.put(null, "value"); // ❌ NullPointerException
// table.put("key", null); // ❌ NullPointerException
table.put("key1", "value1");
table.put("key2", "value2");
// Thread-safe but slow — synchronization on every method
Comparison Table
| Feature | HashMap | Hashtable |
|---|---|---|
| Thread-safe | ❌ No | ✅ Yes (synchronized) |
| Null key | ✅ One null key | ❌ Not allowed |
| Null values | ✅ Multiple | ❌ Not allowed |
| Performance | Fast | Slow (sync overhead) |
| Iterator | Fail-fast | Fail-safe (Enumerator) |
| Introduced | Java 1.2 | Java 1.0 |
| Recommended? | ✅ Yes | ❌ Use ConcurrentHashMap |
Better Alternatives for Thread Safety
Java
// Modern thread-safe HashMap
Map<String, String> safeMap = new ConcurrentHashMap<>();
safeMap.put("key", "value"); // thread-safe, better performance than Hashtable
// Synchronized wrapper (less preferred)
Map<String, String> syncMap = Collections.synchronizedMap(new HashMap<>());
Common HashMap Operations
Java
Map<String, Integer> wordCount = new HashMap<>();
// putIfAbsent — only adds if key doesn't exist
wordCount.putIfAbsent("hello", 0);
// compute — update value
wordCount.compute("hello", (k, v) -> v == null ? 1 : v + 1);
// getOrDefault — safe get with fallback
int count = wordCount.getOrDefault("world", 0);
// forEach — Java 8+
wordCount.forEach((word, cnt) ->
System.out.println(word + ": " + cnt));
// merge — combine values
wordCount.merge("hello", 1, Integer::sum);
