HashMap — not thread-safe, allows null keys/values. HashTable — thread-safe (synchronized), no null keys/values. HashMap is the modern choice.
Analogy: HashMap is like a fast, unlocked filing cabinet — great for single-person use. HashTable is like a filing cabinet with a combination lock — safe for multiple people, but slower because everyone has to wait their turn.
HashMap (java.util.HashMap):
hashCode() + equals() determine bucket placement and equality.1HashMap<String, Integer> map = new HashMap<>();23// Adding entries4map.put("Alice", 90);5map.put("Bob", 85);6map.put(null, 0); // OK — null key allowed7map.put("Charlie", null); // OK — null value allowed89// Retrieving10Integer score = map.get("Alice"); // 9011Integer missing = map.get("Eve"); // null (not found)1213// Checking14boolean hasAlice = map.containsKey("Alice"); // true15boolean hasScore = map.containsValue(90); // true1617// Iterating18for (Map.Entry<String, Integer> entry : map.entrySet()) {19 System.out.println(entry.getKey() + " = " + entry.getValue());20}2122// Java 8+ methods23Integer val = map.getOrDefault("Eve", 0); // 0 if not found24map.putIfAbsent("Alice", 100); // Only adds if key absent25map.computeIfAbsent("Frank", k -> k.length() * 10); // Compute on miss2627// Custom capacity and load factor28HashMap<String, Integer> sized = new HashMap<>(64, 0.5f);29// 64 initial buckets, resize at 50% full
HashTable (java.util.Hashtable):
synchronized.ConcurrentHashMap instead for thread-safe maps (much better performance).1Hashtable<String, Integer> table = new Hashtable<>();23table.put("Alice", 90);4table.put("Bob", 85);56// table.put(null, 0); // THROWS NullPointerException!7// table.put("x", null); // THROWS NullPointerException!89Integer score = table.get("Alice"); // 901011// Enumerations (legacy iteration)12Enumeration<String> keys = table.keys();13while (keys.hasMoreElements()) {14 String key = keys.nextElement();15 System.out.println(key + " = " + table.get(key));16}1718// Better: use Enumeration or for-each19for (String key : table.keySet()) {20 System.out.println(key + " = " + table.get(key));21}
Key differences:
Which thread-safe alternative to use instead of HashTable:
ConcurrentHashMap — best for concurrent reads/writes (segments-based locking).Collections.synchronizedMap(map) — wraps HashMap with synchronization.1// Best thread-safe option2ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();3concurrentMap.put("Alice", 90);4concurrentMap.compute("Alice", (key, val) -> val + 5); // Thread-safe update
Never use HashTable in new code — it's legacy. Use HashMap or ConcurrentHashMap.