为什么Hashtable不带空键? [英] Why does Hashtable not take null key?

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

问题描述

为什么 Hashtable 不接受 null 键?

Why does Hashtable not take a null key?

还有为什么 HashMap 允许 null 键?

Also why does HashMap allow null keys?

让这两个类的关键行为如此不同的目的是什么?

What is the purpose of making these two classes Key behaviour so different?

推荐答案

来自 Hashtable JavaDoc:

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 不能计算一个哈希来将它用作键.

In a nutshell, 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.

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

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

具体来说,在发出 .get(key) 时,使用 null 作为键是这样处理的:

Specifically, the use of null as a key is handled like this when issuing a .get(key):

(key==null ? k==null : key.equals(k))

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

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