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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button