| Point | HashMap | Hashtable | ConcurrentHashMap |
|---|
| Thread safe | No | Yes (locks the whole table) | Yes (fine grained locks) |
| Null key | One allowed | Not allowed | Not allowed |
| Null values | Allowed | Not allowed | Not allowed |
| Speed | Fastest (one thread) | Slow | Fast with many threads |
| Use | Normal code | Old code only | Shared data between threads |
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Main {
static void tryNull(String name, Map<String, String> map) {
try {
map.put(null, "x");
System.out.println(name + ": null key allowed");
} catch (NullPointerException e) {
System.out.println(name + ": null key NOT allowed");
}
}
public static void main(String[] args) {
tryNull("HashMap", new HashMap<>());
tryNull("Hashtable", new Hashtable<>());
tryNull("ConcurrentHashMap", new ConcurrentHashMap<>());
}
}
Output
HashMap: null key allowed
Hashtable: null key NOT allowed
ConcurrentHashMap: null key NOT allowed
Learn more about the similar topics:
| Tutorials |
| No Content Found. |
| Exercises & Assignments |
| No Content Found. |
| Interview Questions & Answers |
| No Content Found. |