基于JDK1.8源码回答-hashtable,concurrenthashmap为什么键和值不能为null,而hashmap可以
1 实验
1.1 HashMap
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put(null, null);
System.out.println(map);
}
1.2 ConcurrentHashMap
public static void main(String[] args) {
ConcurrentHashMap<String ,Object> map = new ConcurrentHashMap<>();
map.put(“12”, null);
}
1.3 Hashtable
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<String, Object>();
hashtable.put(null, “11”);
}
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<String, Object>();
hashtable.put(“11”, null);
}
2 总结
ConcurrentHashMap与HashTable因为在多线程并发的情况下,put操作时无法分辨key是没找到为null,还是key值对应的value为null,所以基于这类情况不允许键值为null。
HashMap是线程不安全的,也就无所谓了。