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