tags:

views:

153

answers:

1

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

+1  A: 

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

Michael Mrozek
@fahd With the rest of the map's values? That seems like the perfect place for it. `foo.put(one, "first value"); foo.put(two, "second value"); foo.put(null, "default value");`
Michael Mrozek
@fahd Sure, but it's convenient to have the default value with the map, so you can pass it elsewhere without needing to include the default value separately
Michael Mrozek