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

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

问题描述

ConcurrentHashMap<的JavaDoc/code> 是这样说的:

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?

我使用了很多 HashMap 来存储数据.但是当更改为 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) 就是那种歧义可能在非并发映射中勉强可以忍受 不能容纳.主要是如果 map.get(key) 返回 null,你无法检测密钥是否显式映射到 null 与密钥不是映射.在非并发地图中,您可以通过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天全站免登陆