Dec 30 2007
How To De-C++-ify Your Java: EnumSet
If you’re still on Java (like me), and you’ve got some enumerations and/or bit flags kicking around (like me), then you really want to know about EnumSet. I just found out about them, and I thought I’d share.
Basically, an EnumSet is a type-safe and readable alternative to bit flags with the same big-O performance characteristics. They look and act like an instance of a boring old Set, which gives you the hooks into the old SetUtils and other Collection-based mojo.
Only four catches I’ve bumped into so far (not bad for a post-1.4 language feature):
- They’re instantiated in a kinda odd way. Instead of using constructors like idiomatic Java, there are some factory methods to use where you pass in the enum class you’re processing or specific elements of the enums you’re working on (e.g. #allOf(Class), #of(first, …rest), #range(from, to)).
- Don’t try to extend the class, because you get wacky exceptions about needing to implement things that aren’t visible.
- The enum is assumed to have a “natural order”, which is assumed to be equivalent to declaration order. There’s no apparent way to override that order or get away from that idea.
- This alert about the iterator kinda spooks me:
The returned iterator is weakly consistent: it will never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the set that occur while the iteration is in progress.
I think this means that if you create an iterator, then change the set, the iterator might or might not reflect the change to the underlying set, and it might or might not explode (as per the Iterator API). Not a big fan of Java ignoring their own API, but I’m willing to take it in my current case.
Popularity: 4% [?]







Iterating over a mutable data structure has always had the thorny issue of what happens when the data structure is mutated part way through the iteration? The only sane answer I’ve ever seen to that is “don’t do that”.