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

subhashis picture subhashis · May 31, 2010 · Viewed 102k times · Source

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

Answer

Michael Mrozek picture Michael Mrozek · May 31, 2010

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