Reputation: 30197
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?
Upvotes: 5
Views: 7825
Reputation: 271
HashMap allows multiple null values but only one null key. If you write multiple null keys like below, then null will be overrides and you'll get the final overridden result. i.e "world"
Map<String, String> valueMap = new HashMap<>();
valueMap.put(null, "hello");
valueMap.put(null, "world");
System.out.println(valueMap.get(null));
Output:
"world"
Upvotes: 0
Reputation: 45
The question has asked about having multiple keys in HashMap which is not possible.
If you pass null again and again the old value is replaced only.
Refer:
Upvotes: 1
Reputation: 2807
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. :)
Upvotes: 5
Reputation: 27232
There's an API call for this:
size: Returns the number of key-value mappings in this map.
hmap.size();
As noted you're just overwriting the key/value pair with a new value.
Upvotes: 4
Reputation: 12135
I would guess you haven't added multiple null
-keys. You just overwrote the same null
key multiple times.
Upvotes: 12
Reputation: 272337
A normal hashmap will have unique keys, so you're overwriting the entry for the null key repeatedly. You won't have multiple identical keys (for this you need a MultiMap or similar)
Upvotes: 7