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. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *