Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of adding a null key or value to a HashMap in Java?

HashMap allows one null key and any number of null values. What is the use of it?

like image 436
subhashis Avatar asked May 31 '10 18:05

subhashis


People also ask

What is the use of null key in HashMap?

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.

What is the purpose of null in Java?

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

Can we add null value in HashMap?

HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.

Which function is used to insert a new key and value into the HashMap?

The put function is used to insert a new key-value pair into a HashMap .


1 Answers

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

like image 78
Michael Mrozek Avatar answered Oct 14 '22 00:10

Michael Mrozek