Wildly unused helper: EnumSet

November 22, 2017 by Michael

Available since Java 1.5 is the nice helper class EnumSet and I still find code like this way to often:

public class Foo {
   enum Thing {
      A, B, C
   }
 
   public static final Set<Thing> THINGS = new HashSet<>();
   static {
      THINGS.add(Thing.A);
      THINGS.add(Thing.B);
      THINGS.add(Thing.C);
   }
}

With Java 9 you could write Set.of(Thing.A, Thing.B, Thing.C) but then you’d miss the optimizations done for enums:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based “bit flags.” Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

As my friend Mark pointed out, it runs in O(1) for small to medium sets:

So, replace the above with

public class Foo {
   enum Thing {
      A, B, C
   }
 
   public static final Set<Thing> THINGS = EnumSet.allOf(Thing.class);
}

Or, if you need immutability, throw in Collections.unmodifiableSet(EnumSet.allOf(Thing.class));. Read operations are passed through anyway.

No comments yet

Post a Comment

Your email is never published nor shared. Required fields are marked *