I'm trying to add C开发者_C百科ards 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:
private static final List<Card> deck = new ArrayList<Card>();
Other problems:
initDeck()
is an instance method, butdeck
is a static reference.initDeck()
is a method on Card.deck
is a static member ofCard
, but a card does not own or define a deck.newDeck
is nonsensical in the face of a static final deck.- Cards should not be delivering decks anyway.
In short, your design is messed up - you need to think more and harder about the entities and their inter-relationships.
It's simple, in your main
method, you're just toString()
an empty ArrayList
. You haven't called initDeck()
method in your main
method at all.
When you ran your program private static final List<Card> deck = new ArrayList<Card>();
, deck was assigned an empty ArrayList
.
it is very suspicious that your deck
is private static final
and your init method public
and non-static
. It can be initialized several times and contain more cards then you would expect. You may want to do the initialization in static block instead.
I would replace the code as follows:
- make the deck
public static final
and unmodifiable (via Collections) - copy the body of your init method in static initializer like this:
static { for (Suit suit : Suit.values()) { for (Rank rank : Rank.values()) { deck.add(new Card(rank, suit)); } } }
- delete
initDeck
completely
It's because initDeck()
isn't called anywhere. Try to replace public void initDeck()
with static
.
The keyword final
in you List<card>
definition is for object that will have an starting value that cannot be changed.
Check it here
精彩评论