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 returnsnullif 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.