13

For an APEX class with:

public class EuchreCard{

    public enum suite {CLUBS, DIAMONDS, HEARTS, SPADES}
    public enum rank {NINE, TEN, JACK, QUEEN, KING, ACE}

}

Is there a way to loop through all enum values? For instance, I want to create a euchre hand, so all I need to do is loop through both suite and rank to generate every possible combination.

2 Answers 2

17
public enum suite {CLUBS, DIAMONDS, HEARTS, SPADES}
public enum rank {NINE, TEN, JACK, QUEEN, KING, ACE}

for(Integer i = 0; i < suite.values().size(); i++)
{
    for(Integer j = 0; j < rank.values().size(); j++)
    {
        system.debug(suite.values()[i] + ' ' + rank.values()[j]);   
    }
}
2
6

I've never used enums before, and I didn't know it had methods like that. cool. :)

I found this too:

https://stackoverflow.com/questions/1104975/for-loop-to-iterate-over-enum-in-java

public class EuchreCard{

    public enum st {CLUBS, DIAMONDS, HEARTS, SPADES}
    public enum rk {NINE, TEN, JACK, QUEEN, KING, ACE}

    public EuchreCard(rk r,st s){
        this.rank=r;
        this.suit=s;
    }//END init

    public static list<EuchreCard> getNewDeck(){
        list<EuchreCard> newDeck=new list<EuchreCard>();

        for(rk r:rk.values()) //<--------  This is where I looped over the enum values
            for(st s:st.values()) //<------  And here
                newDeck.add(new EuchreCard(r,s));
        return newDeck;
    }//END getNewDeck
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .