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

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

问题描述

为什么HashMap不允许 null 键?



> null keys?



使这两个类的行为如此不同是什么?

Hashtable JavaDoc

 要成功存储和检索对象一个散列表,使用
作为键的对象必须实现hashCode方法和equals方法。

简而言之,由于 null isn'对于一个对象,你不能调用 .equals() .hashCode() code> Hashtable 无法计算散列以将其用作密钥。



HashMap 较新,并且具有更多高级功能,这基本上只是对 Hashtable 功能的改进。因此,当创建 HashMap 时,它专门用于处理 null 值作为键,

具体来说, null 作为键的使用在发出 .get(key)

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


Why does Hashtable not take a null key?

Also why does HashMap allow null keys?

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

解决方案

From the 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.

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 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.

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不能取null键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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