sebastiandaschner blog


EnumSet for enum collections

#java friday, january 19, 2018

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.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: