为什么 Hashtable 不允许空键或空值? [英] Why Hashtable does not allow null keys or values?

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

问题描述

如 JDK 文档中所述,Hashtable 不允许空键或空值.HashMap 允许一个空键和任意数量的空值.这是为什么?

As specified in JDK documentation, Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. Why is this?

推荐答案

Hashtable 是较老的类,一般不鼓励使用.也许他们看到了对空键的需求,更重要的是 - 空值,并将其添加到 HashMap 实现中.

Hashtable is the older class, and its use is generally discouraged. Perhaps they saw the need for a null key, and more importantly - null values, and added it in the HashMap implementation.

HashMap 较新,具有更高级的功能,基本上只是对 Hashtable 功能的改进.HashMap 在创建时,专门设计用于将 null 值作为键处理,并将它们作为特殊情况处理.

HashMap is newer, and has more advanced capabilities, which are basically just an improvement on the Hashtable functionality. When HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case.

编辑

来自 Hashtable JavaDoc:

要成功地从 Hashtable 存储和检索对象,用作键的对象必须实现 hashCode 方法和 equals 方法.

To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and the equals method.

由于 null 不是一个对象,你不能在它上面调用 .equals().hashCode(),所以Hashtable 无法计算哈希以将其用作键.

Since null isn't an object, you can't call .equals() or .hashCode() on it, so the Hashtable can't compute a hash to use it as a key.

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

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