Core Java

EnumSet for enum collections

In the last blog post we discovered EnumMaps for mappings with enum keys. You might have observed that there is also a specialized Set that is optimized for enums: EnumSet.

We again define a CoffeeType enum:

public enum CoffeeType {
    ESPRESSO, POUR_OVER, FRENCH_PRESS, LATTE, FLAT_WHITE
}

Now we can create sets of this enum type, by using the EnumSet implementation:

Set<CoffeeType> favoriteCoffeeTypes = EnumSet.of(ESPRESSO, POUR_OVER, LATTE);

assertThat(favoriteCoffeeTypes).containsOnly(ESPRESSO, POUR_OVER, LATTE);

The favoriteCoffeeTypes still acts like any Set, that is, adding duplicates won’t change its contents:

favoriteCoffeeTypes.add(POUR_OVER);

assertThat(favoriteCoffeeTypes).containsOnly(ESPRESSO, POUR_OVER, LATTE);

Interesting side note: If you look into the JDK, you’ll see that EnumSet is implemented by both RegularEnumSet and JumboEnumSet; the number of enum elements determines the implementation being used. If you’re interested in how the EnumSet implementation manage to be highly efficient, I challenge you to have a look into these classes. Hint: Bitwise operations :-)

This post was reposted from my newsletter issue 018.

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: EnumSet for enum collections

Opinions expressed by Java Code Geeks contributors are their own.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button