-3

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

closed as unclear what you're asking by GlenH7, user40980, gnat, ozz, Glenn Nelson Sep 27 '13 at 16:25

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
16

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.

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