I’m trying to add Cards to ArrayList deck, but it doesn’t seem to work(most of the code is an example on oracle.com ). I’m probably doing something really stupid, but I can’t seem to find it.. this is the code:
public class Card {
public enum Rank
{
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE
}
public enum Suit
{
HEARTS, DIAMONDS, SPADES, CLUBS
}
private final Rank rank;
private final Suit suit;
private static final List<Card> deck = new ArrayList<Card>();
public Card(Rank rank, Suit suit)
{
this.suit = suit;
this.rank = rank;
}
// initializes deck
public void initDeck()
{
for (Suit suit : Suit.values())
{
for (Rank rank : Rank.values())
{
deck.add(new Card(rank, suit));
}
}
}
// returns a copy of the deck
public static ArrayList<Card> newDeck()
{
return new ArrayList<Card>(deck);
}
public Rank getRank()
{
return rank;
}
public Suit getSuit()
{
return suit;
}
public String toString()
{
return rank +" of "+ suit;
}
public static void main(String[] args)
{
System.out.println(deck.toString());
}
}
Your problem is that you never actually invoke initDeck, so the deck remains empty, as it was when the static initializer ran:
Other problems:
initDeck()is an instance method, butdeckis a static reference.initDeck()is a method on Card.deckis a static member ofCard, but a card does not own or define a deck.newDeckis nonsensical in the face of a static final deck.In short, your design is messed up – you need to think more and harder about the entities and their inter-relationships.