Ralf Wickum
Ralf Wickum

Reputation: 3270

How to iterate through a Java enum?

I have an enum of string, as in this example.

When my current element would be STRING_ONE, how can switch to the next Strings item in the enum with for instance the ++ operator?

Something like:

 Strings myEnum = String.STRING_ONE;
    myEnum++ ; // to have STRING_TWO for instance

?

EDIT: I do not want to iterate through all of those enum elements. These STRING_ONE, STRING_TWO etc are some sort of states. I want to implement a getNextState() Method like

private void getNextstate(){
   myCurrentstate++;
}

Now, I have this, which does not seem efficient

private void getNextstate(){
   if(myCurrentstate == Strings.STRING_ONE) myCurrentstate == Strings.STRING_TWO;
   else if(myCurrentstate == Strings.STRING_TWO) myCurrentstate == Strings.STRING_THREE;
   //..
   else if(myCurrentstate == Strings.STRING_NINTYNINE) myCurrentstate == Strings.STRING_HUNDRET;
}

Upvotes: 2

Views: 1681

Answers (2)

In java, you can not overload the + operator, but you can for sure do:

   public enum Strings {
    STRING_ONE("ONE"),
    STRING_TWO("TWO")
    ;

    private final String text;

    /**
     * @param text
     */
    private Strings(final String text) {
        this.text = text;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return text;
    }
}

and then

for (Strings dir : Strings.values()) {
  // your code here
  System.out.println(dir.toString());
}

Upvotes: 2

Solorad
Solorad

Reputation: 914

You could use

for (Strings string : Strings.values()) {
    System.out.println(string);
}

Upvotes: 0

Related Questions