HashMap — not thread-safe, allows null. HashTable — thread-safe, no null. HashMap is the modern choice.
Analogy: HashMap is a fast, unlocked filing cabinet. HashTable is a filing cabinet with a lock — safe but slower.
HashMap:
1HashMap<String, Integer> map = new HashMap<>();2map.put("Alice", 90);3map.put("Bob", 85);4map.put(null, 0); // OK — null key5map.put("Charlie", null); // OK — null value67Integer score = map.get("Alice"); // 9089// Java 8+ methods:10Integer val = map.getOrDefault("Eve", 0);11map.putIfAbsent("Alice", 100);12map.computeIfAbsent("Frank", k -> k.length() * 10);1314// Custom capacity:15HashMap<String, Integer> sized = new HashMap<>(64, 0.5f);
HashTable:
synchronized.1Hashtable<String, Integer> table = new Hashtable<>();2table.put("Alice", 90);3// table.put(null, 0); // THROWS NullPointerException!45Integer score = table.get("Alice"); // 9067// Legacy iteration:8Enumeration<String> keys = table.keys();9while (keys.hasMoreElements()) {10 String key = keys.nextElement();11 System.out.println(key + " = " + table.get(key));12}
Key differences:
Better thread-safe alternative:
1// Use ConcurrentHashMap instead of HashTable:2ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();3concurrentMap.put("Alice", 90);4concurrentMap.compute("Alice", (k, v) -> v + 5); // Thread-safe
Never use HashTable in new code — use HashMap or ConcurrentHashMap.