Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through an EnumSet in java?

Tags:

java

loops

enums

When I create an EnumSet and send it via a function, I find myself unable to reach the Enum values set inside the EnumSet. All I can do is compare it to the original set and check if it is present. I do not want that since that forces me to waste lines of code and forces me to reach out for the Original Enum class every single time.

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

    }

I want to iterate through stateCommands and be able to see its content.

How should I proceed with this ?

like image 576
Alexandre Bolduc Avatar asked Feb 07 '12 02:02

Alexandre Bolduc


2 Answers

for(StateCommand command : stateCommands) {
   // do whatever
}

Just like any other Set. Or, if you need to do something more sophisticated, just use the stateCommands.iterator().

like image 104
Louis Wasserman Avatar answered Oct 12 '22 09:10

Louis Wasserman


If you leave the EnumSet generic, the following will NOT work:

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 the EnumSet it will work fine:

public void StateLoop(EnumSet<StateCommand> stateCommands){
    for(StateCommand command : stateCommands) {
       // do whatever
    }
}
like image 40
Quinn Carver Avatar answered Oct 12 '22 10:10

Quinn Carver