为什么ConcurrentHashMap会阻止空键和值? [英] Why does ConcurrentHashMap prevent null keys and values?

查看:121
本文介绍了为什么ConcurrentHashMap会阻止空键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConcurrentHashMap 的JavaDoc这样说:

The JavaDoc of ConcurrentHashMap says this:


喜欢 Hashtable 但不像 HashMap ,此类允许 null 用作键或值。

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

我的问题:为什么?

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

2nd question: why doesn't Hashtable allow null?

我使用了很多HashMaps来存储数据。但是当改为ConcurrentHashMap时,我因为NullPointerExceptions而多次遇到麻烦。

I've used a lot of HashMaps for storing data. But when changing to ConcurrentHashMap I got several times into trouble because of NullPointerExceptions.

推荐答案

来自 ConcurrentHashMap的作者他自己(Doug Lea)

From the author of ConcurrentHashMap himself (Doug Lea):


ConcurrentMaps
(ConcurrentHashMaps,ConcurrentSkipListMaps)中不允许空值的主要原因是$的歧义b $ b可能在非并发地图中几乎不能容忍,不能容纳
。主要的一个是,如果 map.get(key)返回 null ,你
无法检测到键是否显式映射到 null vs键不是
映射。在非并发映射中,您可以通过
map.contains(key)进行检查,但在并发映射中,映射可能已更改
之间的电话。

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.

这篇关于为什么ConcurrentHashMap会阻止空键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆