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)?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With