HashMap allows one null key and any number of null values. What is the use of it?
For HashMap, it allows one null key and there is a null check for keys, if the key is null then that element will be stored in a zero location in Entry array. We cannot have more than one Null key in HashMap because Keys are unique therefor only one Null key and many Null values are allowed.
Null serves as the default value of any uninitialized reference variable, including instance variables and static variables (although you will still receive a compiler warning for uninitialized local variables).
HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.
The put function is used to insert a new key-value pair into a HashMap .
I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):
Map<A, B> foo; A search; B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);
HashMap
handles null keys specially (since it can't call .hashCode()
on a null object), but null values aren't anything special, they're stored in the map like anything else
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