Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the benefit of allowing multiple null keys in hashmap?

Tags:

java

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?

like image 393
sushil bharwani Avatar asked Nov 09 '10 16:11

sushil bharwani


People also ask

Why HashMap allows one null key and multiple null values?

It is not thread-safe and can't be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.

Why do we use null key in HashMap?

It is useful to explicitly store null to distinguish between a key that you know exists but doesn't have an associated value and a key that doesn't exist. An example is a list of registered users and their birthdays.

What happens when we insert null key in HashMap?

When we put a null key to java hashmap hashcode() method is not called on the null, instead puts the key in bucket 0. Java uses linked list to manage multiple objects in the bucket. So if there are already objects in bucket 0, null object will be appended to the linkedlist of bucket 0.

Why is null not allowed in Concurrenthashmap?

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated.


4 Answers

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

like image 96
ZeissS Avatar answered Oct 28 '22 18:10

ZeissS


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)

like image 29
Brian Agnew Avatar answered Oct 28 '22 20:10

Brian Agnew


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. :)

like image 4
Eternal Noob Avatar answered Oct 28 '22 20:10

Eternal Noob


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.

like image 4
Paul Rubel Avatar answered Oct 28 '22 20:10

Paul Rubel