Iterating through EnumSet in java?

When I create an EnumSet and send it through a function, I cannot reach the Enum values ​​set inside the EnumSet. All I can do is compare it with the original kit and check if it is present. I don't want this because it makes me waste lines of code and makes me call for the Original Enum class every time.

for(Action a : Action.values()) { if(stateCommands.contains(a)) { System.out.println(a.getCommand() + a.getDescription()); } } 

I want to iterate through stateCommands and see its contents.

How can I continue this?

+4
source share
2 answers
 for(StateCommand command : stateCommands) { // do whatever } 

Like any other Set . Or, if you need to do something more complex, just use stateCommands.iterator() .

+10
source

If you leave the general EnumSet set, do the following: NOT :

 public void StateLoop(EnumSet stateCommands){ //won't work b/c stateCommands is treated as a generic Object for(StateCommand command : stateCommands) { // do whatever } } 

However, if a type is provided for EnumSet, it will work fine:

 public void StateLoop(EnumSet<StateCommand> stateCommands){ for(StateCommand command : stateCommands) { // do whatever } } 
+1
source

Source: https://habr.com/ru/post/1395139/


All Articles