Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check enumsets for same enum values [duplicate]

I have two EnumSets.

EnumSet.of(A1, A2, A3);
EnumSet.of(A3, A4, A5, A6);

I want to find which values exist in both sets. (In that case, A3.)

Is there any quick way to do that?

like image 900
gts13 Avatar asked Jul 28 '14 13:07

gts13


People also ask

Can you use == on enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

Can two elements in enum have same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can two enums have the same value Java?

Although the language allows multiple enumerators of the same type to have the same value, it is a common expectation that all enumerators of the same type have distinct values. However, defining two or more enumerators of the same type to have the same value can lead to some nonobvious errors.


2 Answers

EnumSet is a Set. So you can probably use retainAll method to get the intersection.

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Note that this will modify the existing collection. If you don't want that, you can create a copy. If that's not a good option for you, you can look for other solutions.

like image 50
Swapnil Avatar answered Sep 20 '22 23:09

Swapnil


EnumSet A = EnumSet.of(A1, A2, A3);
EnumSet B = EnumSet.of(A3, A4, A5, A6);

EnumSet intersection = EnumSet.copyOf(A);

intersection.retainAll(B);

retainAll modifies the underlying set so create a copy.

like image 28
another_dev Avatar answered Sep 22 '22 23:09

another_dev