为什么在哈希映射中有空值或空键很有用?

Why is it useful to have null values or null keys in hash maps?(为什么在哈希映射中有空值或空键很有用?)

本文介绍了为什么在哈希映射中有空值或空键很有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hashtable 不允许空键或空值,而 HashMap 允许空值和 1 个空键.

问题:

  1. 为什么会这样?
  2. 在 HashMap 中有这样的键和值有什么用?

解决方案

1.为什么会这样?

HashMap 比 Hashtable 更新,并修复了它的一些限制.

我只能猜测设计师的想法,但以下是我的猜测:

  • Hashtable 通过调用 hashCode.如果键为空,这将失败,因此这可能是不允许空作为键的原因.
  • 方法Hashtable.get 如果键不存在,则返回 null.如果 null 是一个有效值,那么 null 是否意味着该键存在但值为 null,或者该键不存在,这将是模棱两可的.模棱两可很糟糕,因此这可能是不允许将空值作为值的原因.

但事实证明,有时您确实想要存储空值,因此在 HashMap 中取消了限制.以下警告也包含在 HashMap.get:

<块引用>

返回值为 null 并不一定表示该映射不包含该键的映射;也有可能映射显式地将键映射到 null.

<小时><块引用>

2.在 HashMap 中有这样的键和值有什么用?

显式存储 null 以区分您知道存在但没有关联值的键和不存在的键是有用的.一个例子是注册用户列表和他们的生日.如果您询问特定用户的生日,您希望能够区分该用户不存在和存在但未输入生日的用户.

我想不出任何(好的)理由想要将 null 存储为密钥,一般来说我建议不要使用 null 作为密钥,但大概在某个地方至少有一个人需要该密钥可以为空.

Hashtable does not allow null keys or values, while HashMap allows null values and 1 null key.

Questions:

  1. Why is this so?
  2. How is it useful to have such a key and values in HashMap?

解决方案

1. Why is this so?

HashMap is newer than Hashtable and fixes some of its limitations.

I can only guess what the designers were thinking, but here are my guesses:

  • Hashtable calculates a hash for each key by calling hashCode on each key. This would fail if the key were null, so this could be a reason for disallowing nulls as keys.
  • The method Hashtable.get returns null if the key is not present. If null were a valid value it would be ambiguous as to whether null meant that the key was present but had value null, or if the key was absent. Ambiguity is bad, so this could be a reason for disallowing nulls as values.

However it turns out that sometimes you do actually want to store nulls so the restrictions were removed in HashMap. The following warning was also included in the documentation for HashMap.get:

A return value of null does not necessarily indicate that the map contains no mapping for the key; it is also possible that the map explicitly maps the key to null.


2. How is it useful to have such a key and values in HashMap?

It is useful to explicitly store null to distinguish between a key that you know exists but doesn't have an associated value and a key that doesn't exist. An example is a list of registered users and their birthdays. If you ask for a specific user's birthday you want to be able to distinguish between that user not existing and the user existing but they haven't entered their birthday.

I can't think of any (good) reason for wanting to store null as a key, and in general I'd advise against using null as a key, but presumably there is at least one person somewhere that needs that keys that can be null.

这篇关于为什么在哈希映射中有空值或空键很有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么在哈希映射中有空值或空键很有用?

基础教程推荐