Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Hashtable not take null key?

Why does Hashtable not take a null key?

Also why does HashMap allow null keys?

What is the purpose of making these two classes Key behaviour so different?

like image 578
BOSS Avatar asked Sep 26 '11 14:09

BOSS


People also ask

Can HashTable have null keys?

Hashtable does not allow null keys but HashMap allows one null key and any number of null values.

Why HashMap allows one null key and multiple null values?

For HashMap, it allows one null key and there is a null check for keys, if the key is null then that element will be stored in a zero location in Entry array. We cannot have more than one Null key in HashMap because Keys are unique therefor only one Null key and many Null values are allowed.

Which of these does not allow null keys?

So to summarize, Hashtable doesn't allow null key to compute the bucket index. HashMap is newer where it has corrected the issues in Hashtable and allows one null key and value.

What happens if we insert null key in HashMap?

When you put NULL to HashMap there is special check if you are trying to put NULL as key (called putForNullKey()). It is special case and works not like you are trying to put some object which is not null, and as you may see it even doesn't go to hash calculation.


2 Answers

From the Hashtable JavaDoc:

To successfully store and retrieve objects from a hashtable, the objects used 
as keys must implement the hashCode method and the equals method.

In a nutshell, since null isn't an object, you can't call .equals() or .hashCode() on it, so the Hashtable can't compute a hash to use it as a key.

HashMap is newer, and has more advanced capabilities, which are basically just an improvement on the Hashtable functionality. As such, when HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case.

Specifically, the use of null as a key is handled like this when issuing a .get(key):

(key==null ? k==null : key.equals(k))
like image 120
cdeszaq Avatar answered Oct 07 '22 03:10

cdeszaq


It is just an implementation detail.

Hashtable is the older class, and its use is generally discouraged. Perhaps they saw the need for a null key, and more importantly - null values, and added it in the HashMap implementation.

like image 28
Bozho Avatar answered Oct 07 '22 04:10

Bozho