问题
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
回答1:
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.
回答2:
It's one of the differences between a Hashtable and a HashMap.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
Usually, we use the null key to represent the default case (i.e. the value that should be used if a given key isn't present)
回答3:
HashMap allows only one null key. So whenever any one want to put some value with null it calls putForNullKey method inside the put method and in putForNullKey method it places the value at zero index.
For getting value by null key it also has a method getForNullKey which it calls from inside the get method.
来源:https://stackoverflow.com/questions/16152596/what-does-putfornullkey-method-do-inside-the-put-method-in-hashmap