java - 为什么 ConcurrentHashMap 会阻止 null 键和值?

标签 java concurrenthashmap

ConcurrentHashMap 的 JavaDoc是这样说的:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

我的问题:为什么?

第二个问题:为什么Hashtable不允许null?

我使用了很多 HashMap 来存储数据。但是当更改为 ConcurrentHashMap 时,由于 NullPointerExceptions,我遇到了几次麻烦。

最佳答案

From the author of ConcurrentHashMap himself (Doug Lea) :

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

关于java - 为什么 ConcurrentHashMap 会阻止 null 键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698638/

相关文章:

java - 在objectdb中查询

java - ConcurrentHashMap 值变空

java - 我们可以创建 hashmap 键单例吗?

java - Collectors.toConcurrentMap 和通过 Collectors.toMap 供应商选项将 Map 转换为 ConcurrentHashMap 之间有什么区别?

Java-ThreadLocal 与 ConcurrentHashMap

java - 从工作区的文件夹中检索文件

java - 如何在 Java 中将公历转换为 Unix 时间?

java - 在 TomCat 服务器上使用 JavaServlets 的 Cronjob

java - 任意键的锁定处理程序

java - Java中如何检查4位数字代码中是否有双字母