When would I use java Collections singletonMap method?
I don't understand why you would need java Collections singletonMap? Is it useful in multithreaded ap开发者_如何学运维plications?
Basically, it allows you to do this:
callAPIThatTakesAMap(Collections.singletonMap(key, value));
rather than this:
Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key, value);
callAPIThatTakesAMap(m);
which is much nicer when you only have a single key/value pair. This situation probably does not arise very often, but singleton()
and singletonList()
can quite frequently be useful.
It is useful if you need to pass a map to some general code (as a parameter, or as a result from a method) and you know that in this particular case -- but perhaps not in other cases that pass map to the same general code -- the map you want to pass has only a single key. In that case, the SingletonMap is more efficient than a full-blown map implementation, and also more convenient for the programmer because everything you need to say can be said in the constructor.
Also, a SingletonMap implementation returned by Collections.singletonMap() has a smaller memory footprint than a regular HashMap. It only has to contain two member fields: the key and the value, whereas a HashMap maintains an internal array of Node objects plus other member fields. So if you are creating a lot of these maps in memory, it would be a prudent choice to use Collections.singletonMap().
many answers told you when, but I want to point out when to not use it
don't use it if you want to put items later on
,
because put implementation of singletonMap
will throw UnsupportedOperationException
It's mainly for convenience and abstraction. Some APIs take a Collection
as an argument and it's nice to have a simple way to convert objects to a Set
or Map
.
singletonMap()
and singletonList()
were actually introduced after singletonSet()
in Java 1.3 because singletonSet()
proved to be useful.
This is just another example, but I wrote this line of code:
@Override public Map<Action, Promise<Boolean>> actOnResults() throws Exception {
return Collections.singletonMap(Action.UPDATE_DATABASE, saver.save(results));
}
note the @Override
. The interface more generally can take maps of many things; this particular instantiation just always returns a map containing one thing. Also note that the key to the map is an Enum. So the maps are never supposed to be big, they're just supposed to contain the results of whichever actions are specified. In my real example there are up to 5 actions, and this instantiation only uses one of them.
To be complete, EnumSet
or EnumMap
is often appropriate in these cases, but those are still annoyingly verbose compared to the code above.
精彩评论