简体   繁体   中英

checking for null in Hashtable get() operation

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);
   }

why it is using if (n != null) { during get() operation in above code when Hashtable does not allow nulls in keys and values?

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?

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.

如果地图/表中没有键,则返回null。

You could write

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

while this is clearer it has two problems.

  1. It is slower because it accesses the map twice.
  2. It has a potential race condition if the collection is updated in another thread.

Given the thread safe Hashtable has been chosen, it appears that performance was less important than thread safety so the second reason is more likely.

get返回如果指定的键不存在,则返回Null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM