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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3622007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:48:07  来源:igfitidea点击:

Why is it useful to have null values or null keys in hash maps?

javahashmap

提问by sab

Hashtabledoes not allow null keys or values, while HashMapallows null values and 1 null key.

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

Questions:

问题:

  1. Why is this so?
  2. How is it useful to have such a key and values in HashMap?
  1. 为什么会这样?
  2. 在 HashMap 中拥有这样的键和值有什么用?

采纳答案by Mark Byers

1. Why is this so?

1. 为什么会这样?

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

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

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

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

  • Hashtable calculates a hash for each key by calling hashCodeon each key. This would fail if the key were null, so this could be a reason for disallowing nulls as keys.
  • The method Hashtable.getreturns 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.
  • Hashtable 通过调用每个键来计算每个键的哈希值hashCode。如果键为空,这将失败,因此这可能是不允许将空作为键的原因。
  • Hashtable.get如果键不存在,该方法返回 null。如果 null 是一个有效值,那么对于 null 是否意味着键存在但值为 null,或者键是否不存在,这将是模棱两可的。歧义是不好的,因此这可能是不允许将空值作为值的原因。

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:

然而事实证明,有时您确实想要存储空值,因此在 HashMap 中删除了限制。文档中还包含以下警告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.

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



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

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

It is useful to explicitly store null to distinguish between a key that you knowexists 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.

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

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.

我想不出任何(好的)理由想要将 null 作为键存储,一般来说我建议不要使用 null 作为键,但据推测,某处至少有一个人需要该键空值。

回答by sinuhepop

Well, I think Mark Byers answered perfectly, so just a simple example where null values and keys can be useful:

好吧,我认为 Mark Byers 回答得很好,所以只是一个简单的例子,其中空值和键可能有用:

Imagine you have an expensive function that always returns the same result for the same input. A map is a simple way for caching its results. Maybe sometimes the function will return null, but you need to save it anyway, because the execution is expensive. So, null values must be stored. The same applies to null key if it's an accepted input for the function.

想象一下,你有一个昂贵的函数,它总是为相同的输入返回相同的结果。地图是一种缓存其结果的简单方法。也许有时函数会返回null,但无论如何你都需要保存它,因为执行成本很高。因此,必须存储空值。如果它是函数的可接受输入,则同样适用于 null 键。

回答by Amit Agrawal

In addition to what answered by Mark Bayers,, Null is considered as data and it has to be stored as a value for further checking. In many cases null as value can be used to check if key entry is there but no value is assigned to it, so some action can be taken accordingly. This can be done by first checking if key is there, and then getting value. There is one more case in which just put whatever data is coming(without any check). All the checks are applied to it after getting it.

除了 Mark Ba​​yers 回答的内容,Null 被视为数据,必须将其存储为值以供进一步检查。在许多情况下,可以使用 null 作为值来检查是否存在键条目但没有为其分配值,因此可以采取相应的措施。这可以通过首先检查键是否存在,然后获取值来完成。还有一种情况,就是把即将到来的任何数据都放进去(不做任何检查)。得到它后,所有的检查都适用于它。

Whereas null as a key, i think can be used to define some default data. Usually null as a key does not make much sense.

而 null 作为键,我认为可以用来定义一些默认数据。通常 null 作为键没有多大意义。

回答by user3207104

Sir HashMap is also internally uses hashCode() method for inserting an element in HashMap, so I think this will be not the proper reason for "why HashTable allow null key"

HashMap 爵士也在内部使用 hashCode() 方法在 HashMap 中插入元素,所以我认为这不是“为什么 HashTable 允许空键”的正确原因

回答by Xinchao

It will make the Map interface easier to use / less verbose. nullis a legitimate value for reference types. Making the map able to handle null keys and values will eliminate the need for null checking before calling the api. So the map api create less "surprises" during runtime.

它将使 Map 界面更易于使用/不那么冗长。null是引用类型的合法值。使映射能够处理空键和值将消除在调用 api 之前进行空检查的需要。因此,地图 api 在运行时创建的“惊喜”更少。

For example, it is common that map will be used to categorize a collection of homogeneous objects based a single field. When map is compatible with null, the code will be more concise as it is just a simple loop without any if statement (of course you will need to make sure the collection does not have null elements). Fewer lines of code with no branch / exception handling will be more likely to be logically correct.

例如,通常使用 map 对基于单个字段的同类对象集合进行分类。当 map 与 null 兼容时,代码将更加简洁,因为它只是一个没有任何 if 语句的简单循环(当然您需要确保集合没有 null 元素)。没有分支/异常处理的更少代码行将更有可能在逻辑上是正确的。

On the other hand, not allowing null will not make the map interface better/safer/easier to use. It is not practical to rely on the map to reject nulls - that means exception will be thrown and you have to catch and handle it. Or, to get rid of the exception you will have to ensure nothing is null before calling the map methods - in which case you don't care if map accepts null since you filtered the input anyway.

另一方面,不允许 null 不会使地图界面更好/更安全/更易于使用。依靠映射来拒绝空值是不切实际的 - 这意味着将抛出异常并且您必须捕获并处理它。或者,要摆脱异常,您必须在调用 map 方法之前确保没有任何内容为 null - 在这种情况下,您不关心 map 是否接受 null,因为您无论如何都过滤了输入。

回答by shubham malik

HashTable is very old class , from JDK 1.0.The classes which are in place from JDK 1.0are called Legacyclasses and by default they are synchronized.

HashTable 是一个非常古老的类,来自 JDK 1.0。JDK 1.0 中存在的类称为Legacy类,默认情况下它们是同步的

To understand this, first of all you need to understand comments written on this class by author. “This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.”

要理解这一点,首先你需要理解作者在这个类上写的评论。“这个类实现了一个哈希表,它将键映射到值。任何非空对象都可以用作键或值。要成功地从哈希表中存储和检索对象,用作键的对象必须实现 hashCode 方法和 equals 方法。”

HashTable class is implemented on hashing mechanism, means to store any key-value pair, its required hash code of key object. HashTable calculates a hash for each key by calling hashCode on each key. This would fail If key would be null, it will not be able to give hash for null key, it will throw NullPointerExceptionand similar is the case for value, throwing null if the value is null.

HashTable 类是在哈希机制上实现的,意味着存储任何键值对,其所需的键对象的哈希码。HashTable 通过对每个键调用 hashCode 来计算每个键的哈希值。这将失败如果 key 为 null,它将无法为 null 键提供哈希值,它将抛出NullPointerException和 value 的情况类似,如果 value 为 null 则抛出 null

But later on it was realised that null key and value has its own importance, then revised implementations of HashTable were introduced like HashMap which allow one null key and multiple null values.

但后来意识到空键和空值有其自身的重要性,于是引入了 HashTable 的修改实现,如 HashMap 允许一个空键和多个空值。

For HashMap, it allows one null key and there is a null check for keys, if the key is null then that element will be stored in a zero location in Entry array.

对于 HashMap,它允许一个空键,并且对键进行空检查,如果键为空,则该元素将存储在 Entry 数组中的零位置。

We cannot have more than one Null key in HashMap because Keys are uniquetherefor only one Null key and many Null values are allowed.

在 HashMap 中我们不能有多个 Null 键,因为Key 是唯一的,因此只有一个 Null 键并且允许多个 Null 值。

USE- Null key we can use for some default value.

USE- 我们可以用于一些默认值的空键。

Modified and better implementation of HashTable was later introduced as ConcurrentHashMap.

HashTable 的修改和更好的实现后来被引入为ConcurrentHashMap