为什么在散列映射中有空值或空键是很有用的? [英] Why is it useful to have null values or null keys in hash maps?

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

问题描述

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



问题:




  1. 为什么会这样?

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


解决方案


1。为什么会这样?


HashMap比Hashtable更新,并修复了一些限制。



我只能猜测设计师在想什么,但这里是我的猜测:


  • Hashtable为每个键计算一个散列通过调用 hashCode 。如果密钥为空,这可能会失败,所以这可能是禁止将空值作为密钥的原因。
  • 方法 Hashtable.get 将返回null,如果密钥不存在。如果null是一个有效的值,那么null是否意味着密钥存在,但是值为null,或者如果密钥不存在,则会是模糊的。歧义是不好的,所以这可能是阻止空值为值的原因。



然而事实证明,有时候你确实想要存储空值,以便在HashMap中删除限制。以下警告也包含在 HashMap.get


null的返回值不一定表示该映射不包含该键的映射;






$ b也可能映射将键明确映射为空。 $ b <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.

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

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