2012-07-23 119 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已被選中,看起來性能並不比線程安全更重要,所以第二個原因更有可能。