在Hashtable get()操作中检查null [英] checking for null in Hashtable get() operation
问题描述
根据类 Hashtable
的java docs:
According to java docs for class Hashtable
:
This example creates a hashtable of numbers. It uses the names of the numbers as keys:
Hashtable<String, Integer> numbers
= new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
To retrieve a number, use the following code:
Integer n = numbers.get("two");
if (n != null) {
System.out.println("two = " + n);
}
为什么使用 if(n!= null ){
在上述代码中的get()操作期间,Hashtable不允许键和值中的空值?
why it is using if (n != null) {
during get() operation in above code when Hashtable does not allow nulls in keys and values?
它会OK,因为HashMap允许键和值的空值,但为什么它使用它为Hashtable?
Had it been written for HashMap then it would be OK as HashMap allow nulls in keys and values but why it is using it for Hashtable?
推荐答案
自 如果指定的键在Hashtable中不存在,则get()
方法返回 null
。
在上面的代码示例中,我们可以省略这一点,因为我们知道两个
键是存在的,但是在现实生活应用中通常不是这样。
It is just good practice since the get()
method returns null
if the specified key doesn't exist in the Hashtable.
In the above code example we could omit this since we know that the "two"
key is there, but that is often not the case in real life applications.
这篇关于在Hashtable get()操作中检查null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!