sushil bharwani
sushil bharwani

Reputation: 30197

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?

Upvotes: 5

Views: 7825

Answers (6)

Shubham Chaudhary
Shubham Chaudhary

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

Neelesh Shukla
Neelesh Shukla

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:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29

Upvotes: 1

Eternal Noob
Eternal Noob

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

Paul Rubel
Paul Rubel

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

ZeissS
ZeissS

Reputation: 12135

I would guess you haven't added multiple null-keys. You just overwrote the same nullkey multiple times.

Upvotes: 12

Brian Agnew
Brian Agnew

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

Related Questions