How's about Collections.getSafe(...) for Map<?, ?>, which wouldn't return null?
David Holmes
David.Holmes at Sun.COM
Mon Oct 26 16:07:14 UTC 2009
Hi Paul,
Paul Benedict wrote:
> Since we're talking Map, I think a more utility would be gained by
> including putIfAbsent (see java.util.concurrent) because I see many
> lines of code that do that idiom all the time.
>
> This idiom is especially prevalent when the value is itself a nested collection.
>
> Map<Object, List<Object>> map = ...
> List<Object> collection = map.get(key);
> if (collection == null) {
> collection = new LinkedList<Object>();
> map.put(key, collection);
> }
> collection.add(value);
I suspect Remi referred to closures to have a way to let the user define
what should happen in place of "new LinkedList" above.
The ConcurrentMap.putIfAbsent takes the potentially inserted object as a
parameter and you have to take special steps to try to avoid unnecessary
contruction (google Memoizer).
My main concern about non-concurrent putIfAbsent is that it is
non-concurrent and I would not want users to get the two confused.
Just 2c.
David Holmes
More information about the core-libs-dev
mailing list