GFauxPas GFauxPas - 3 months ago 9
Java Question

Creating all possible playing cards (a deck)

Let's say I'm trying to simulate playing with standard playing cards.

I have something like this:

class Face {
Set<Character> Faces = new HashSet<Character>(
Arrays.asList('2','3','4','5','6','7','8','9','T','J', 'Q', 'K', 'A')
);
}


and something like this:

public enum Suit { HEART, DIAMONDS, SPADES, CLUBS }


How would I create a collection, such as a set or linked list, of objects that collection is best suited for this, and what type of object each pair in the collection should be. I can think of several inelegant ways to approach this, such as a linked list of arrays of length 2, but I'm asking what the "best" way to do this is.

I'm not averse to using streams.

Answer

Just as @Progressive_overload commented, this would probably be the best approach.

Card Class:

enum Suit {HEART, DIAMONDS, SPADES, CLUBS}
enum Rank {TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE}
class Card {
   public Rank rank;
   public Suit suit;

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

Generate:

List<Card> deck = new ArrayList<Card>();

for (Suit s : Suit.values()) {
  for (Rank r : Rank.values()) {
    deck.add(new Card(r, s));
  }
}
Comments