Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Reasons for Allowing null as a HashMap Key?

Tags:

java

Why Java decided to allow 'null' as a key in HashMap? As we know hashcode() can't be calculated on null value. Is there any design consideration for this decision to allow null key in HashMap which is not there in Hashtable(Other than considering as a default value)?

like image 765
Sivasubramaniam Arunachalam Avatar asked Mar 28 '12 17:03

Sivasubramaniam Arunachalam


People also ask

Why null key is allowed in HashMap?

It is useful to explicitly store null to distinguish between a key that you know exists but doesn't have an associated value and a key that doesn't exist. An example is a list of registered users and their birthdays.

Can we put null as key in map java?

Indeed, if a Java Map implementation allows for null values, then it is possible for the Map to return its value for the given key, but that value might be a null. Often this doesn't matter, but if it does, one can use Map. containsKey() to determine if the Map entry has a key entry.

Why HashTable not allow null but HashMap allow?

As specified in JDK documentation, Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. Why is this? because key can't be duplicated in a single map.


1 Answers

From the JDK 1.2 Java Collections API Change Summary (not sure where to find the official version on Oracle's website):

Added null-key support to HashMap. This was done for consistency with TreeMap and the late, unlamented ArrayMap, and because customers requested it. Now all of our general-purpose collection implementations accept null keys, values and elements.

Joshua Bloch and Doug Lea disagreed on this, and this caused problems for concurrent hash maps.

like image 174
Bruno Avatar answered Sep 21 '22 09:09

Bruno