Q:

What does `putForNullKey` method do inside the `put` method in hashmap?

Today I was fixing one defect and found a very interesting thing.
I was trying to put a key value pair in hashmap. (I was assuming that key is there but later it was found to be null).
So while retrieving the value using a key , I was not getting null every time.
Later I found that key is null , I corrected it.
But then I see the code for put method of Hashmap.
Why does it does not gives an exception when the key is null ?
It calls putForNullKey private method. What does it do?
But i am thinking it should give some exception if the key is null.
Why they have not implemented it like that?
Key Value pair is not useful if a key is null?
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29

A:

From the Javadoc for HashMap:
Hash table based implementation of the Map interface.
This implementation provides all of the optional map
operations, and permits null values and the null key

This is by design, and it is documented. The 'why' question is hard to answer, but it has been that way since HashMap (and before that, Hashtable) were introduced (Edit, actually, Hashtable did not allow nulls).
As to why it has the putForNullKey, well HashMap relies on the hashCode() of a key to place it, and, since it can't get the hashCode() from a null value, it has to do it as a special case.

