为什么Hashtable不能取null键? [英] Why does Hashtable not take null key?
问题描述
为什么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屋!