Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Java EnumSets

Tags:

java

enumset

If I have an Enum, I can create an EnumSet using the handy EnumSet class

enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
EnumSet<Suit> reds = EnumSet.of(Suit.HEARTS, Suit.DIAMONDS);
EnumSet<Suit> blacks = EnumSet.of(Suit.CLUBS, Suit.SPADES);

Give two EnumSets, how can I create a new EnumSet which contains the union of both of those sets?

EnumSet<Suit> redAndBlack = ?

like image 274
Alex Spurling Avatar asked Sep 07 '10 11:09

Alex Spurling


People also ask

When to use EnumSet in Java?

Methods of Java EnumSet class It is used to create an empty enum set with the specified element type. It is used to create an enum set initially containing the specified element. It is used to create an enum set initially containing the specified elements. It is used to return a copy of this set.

What is EnumSet in Java?

An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet: Even though AbstractSet and AbstractCollection provide implementations for almost all the methods of the Set and Collection interfaces, EnumSet overrides most of them.

How do you create an empty EnumSet in Java?

Use EnumSet. noneOf(Class) to create an empty EnumSet.

When to use enum set?

The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. A few important features of EnumSet are as follows: It extends AbstractSet class and implements Set Interface in Java. EnumSet class is a member of the Java Collections Framework & is not synchronized.


1 Answers

An EnumSet is also a collection, so you can use many of the Collection API calls as well, such as addAll.

EnumSet<Suit> redAndBlack = EnumSet.copyOf(reds);
redAndBlack.addAll(blacks);
like image 189
tschaible Avatar answered Oct 02 '22 04:10

tschaible