VOOZH about

URL: https://www.javacodegeeks.com/2018/01/enumset-enum-collections.html

⇱ EnumSet for enum collections - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
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 ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Sebastian Daschner
Sebastian Daschner
January 22nd, 2018Last Updated: January 23rd, 2018
0 100 1 minute read

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

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

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz