1

Is there a way to iterate through all the elements of an enum to add them into a LinkedList?

The example that I'm trying to do: I'm making a deck of cards. I have 2 enums: rank and value. Using a nested for loop, I want to have every card of the deck added into the ArrayList, using the 2 enums.

Thanks!

1
  • So you want every permutation of the two enums? Commented Feb 5, 2015 at 22:52

5 Answers 5

3

You can simply use the .values() static function of the enum class.

You could use:

for(Rank rank : Rank.values()) {
  for (Value val : Value.values()) {
    // stuff
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

enum Rank { ... }

enum Suit { ... }

class Card {
    Rank rank;
    Suit suit;

    Card(Rank r, Suit s) { rank = r; suit = s; }
}

Then later..

List<Card> all() {
    List<Card> cards = new ArrayList<>();
    for (Rank r : Rank.values()) {
        for (Suit s : Suit.values()) {
            cards.add(new Card(r, s));
        }
    }

    return cards;
}

Comments

1

First thing you'll need to do is to create a Card class.

Once you have that, loop through each element of the first enum (use .values() to get each element), and for each element, loop through each element of the second enum. In that second loop, create a new Card with those values.

Comments

1

I think you want something like this:

for(Rank r : Rank.values()){
    for(Value v : Value.values()) {
        // new Car(r, v);
    }
}

This assumes you have a Card class, with a constructor that takes each enum as a parameter. You'd also need a list or other collection to hold the cards.

Comments

1

Enums have the values() method, which returns an array of the instances.

Use two nested foreach loops:

List<Card> deck = new LinkedList<>();
for (Suit suit : Suit.values())
    for (Rank rank : Rank.values())
        deck.add(new Card(suit, rank));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.