2012-07-23 121 views
2

根据Java文档的Hashtable类:在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); 
    } 

为什么它使用get期间if (n != null) {在上面的代码()操作时的Hashtable不允许在键和值空?

如果它是为HashMap编写的,那么它会好的,因为HashMap允许在键和值中使用空值,但为什么它将它用于Hashtable?

回答

5

这只是一个良好的做法,因为如果指定的键不存在于Hashtable中,get()方法返回null
在上面的代码示例中,我们可以省略这个,因为我们知道"two"键在那里,但在现实生活中通常不是这种情况。

3

如果密钥不存在于映射/表中,则返回null。

1

得到返回NULL作为值,如果指定的键不存在

3

你可以写

if (number.containsKey("two")) { 
    Integer n = numbers.get("two"); 
    System.out.println("two = " + n); 
} 

而这是更清楚它有两个问题。

  1. 它比较慢,因为它访问地图两次。
  2. 如果集合在另一个线程中更新,则它有潜在的争用条件。

鉴于线程安全的Hashtable已被选中,看起来性能并不比线程安全更重要,所以第二个原因更有可能。