Search code examples
javahashmap

Whats the benefit of allowing multiple null keys in hashmap?


Just for experimenting, I added multiple null keys in a Hashmap instance. And it didn't complain. What's the benefit of doing that?

The code is,

Map hmap = new HashMap();
hmap.put("sushil","sushil11" );
hmap.put(null,null);
hmap.put(null,"king");
hmap.put(null,"nagasaki");
hmap.put(null,null);

How many keys are there in the map?


Solution

  • It is used to get switch:case:default behavior.

    Example:

    Problem Definition: Coffee shop in CS Department building. They provide coffee to CS Student for $1.00, to IT department students $1.25 and others for $1.50.

    Then Map will be:

    Key -> Value

    IT -> 1.25

    CS -> 1.00

    null -> 1.50

    if(map.containsKey(dept))

    price = map.get(dept);

    else

    price = map.get(null);

    P.S. - I am not "Department-ist" if that's a word. :)