I have two EnumSet
s.
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?
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.
CA1069: Enums should not have duplicate values.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With