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?
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.
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.
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.
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.
I would guess you haven't added multiple null
-keys. You just overwrote the same null
key multiple times.
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)
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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With