HashMap — not thread-safe, allows null. HashTable — thread-safe, no null. Use HashMap or ConcurrentHashMap.
Analogy: HashMap = fast unlocked cabinet. HashTable = locked cabinet (safe but slow).
HashMap:
1HashMap<String, Integer> map = new HashMap<>();2map.put("Alice", 90);3map.put(null, 0); // OK4map.put("Bob", null); // OK56Integer score = map.get("Alice");78// Java 8+:9map.getOrDefault("Eve", 0);10map.putIfAbsent("Alice", 100);11map.computeIfAbsent("Frank", k -> k.length() * 10);1213// Custom sizing:14new HashMap<>(64, 0.5f);
HashTable:
1Hashtable<String, Integer> table = new Hashtable<>();2table.put("Alice", 90);3// table.put(null, 0); // NullPointerException!45Integer score = table.get("Alice");67Enumeration<String> keys = table.keys();8while (keys.hasMoreElements()) {9 String key = keys.nextElement();10 System.out.println(key + " = " + table.get(key));11}
Differences:
Better alternative:
1ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();2map.put("Alice", 90);3map.compute("Alice", (k, v) -> v + 5); // Thread-safe
Never use HashTable — use HashMap or ConcurrentHashMap.