A HashMap allows only one null key. Is it because it allows only unique keys? Or is there another reason?

  • 11
    Related HashMap null key. Food for thought - how do you distinguish two 'different' nulls? What does two different nulls mean? – user40980 Sep 23 '13 at 18:43
  • 3
    What's confusing about it? A hash is a key/value pair. You use the key to look up the value. If you have multiple of the same key, how do you know which one to grab to get the value? Thus, if NULL is a key, and you can use it to look up a value, how do you expect to look up a value if there are multiple NULL keys? – kenzietech Sep 23 '13 at 20:07
  • 2
    Are you confusing key with value perhaps? A HashMap can have multiple null values, which can have some use e.g. with containsKey() (to distinguish null values from absent keys). – Will Sep 23 '13 at 22:05

Why is it confusing? The javadoc for HashMap.put clearly states:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

It clearly states what happens when you do a put with a key which was already in the map. The specific case of key == null behaves in the same way: you can't have two different mappings for the null key (just like you can't for any other key). It's not a special case, for the context of your question.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.