Monday, December 28, 2009

Handy But Hidden: Collections.newSetFromMap()

I was reminded again today of how much the core Java libraries have grown over the years.  It can be really hard to keep track of all the nice little features that get added in each release.  Today, I was wishing that there was a ConcurrentHashSet class or some other HashSet-style concurrent collection.  Before implementing something myself, I did some searching on Google and found a nice way to solve the problem.  In Java 6 (a.k.a. JDK 1.6), Sun added the utility method Collections.newSetFromMap(), which allows you to pass in an empty backing Map and get out a Set with behavior based on the underlying Map.  So, here is all I needed to do to build a concurrent HashSet:

Set<Observer> observers = Collections.newSetFromMap(new ConcurrentHashMap<Observer, Boolean>());

I also found a bug/enhancement request in Sun's bug database suggesting that this feature should be documented in any core Map for which there is no corresponding Set implementation, such as WeakHashMap and IdentityHashMap.  Given how long I went without knowing the method existed, I wish they'd done it.


Post a Comment