java enum到arraylist卡片组

时间:2013-12-11 23:48:33

标签: java arraylist enums

问题:只有内存地址是out.print of arraylist。例如:Card @ 14318bb。

我真的希望这是一个新问题。我看了看,阅读和学习,但似乎仍然有一个扭曲!代码:

DeckMain.java

public class DeckMain {
    public static void main(String[] args) {
        List<Card> newDeck = new ArrayList<Card>( );

        Card.Rank[] ranks = Card.Rank.values();  
        Card.Suit[] suits = Card.Suit.values(); 

        for (Card.Suit suit : suits) {
            for (Card.Rank rank : ranks) {
                newDeck.add(new Card(rank, suit));
            }
        }

        int n = newDeck.size();

        for (int i = 0; i < n ; i++) {
            System.out.println((i + 1)  + ": " + newDeck.get(i));       
        }
    }
}

Card.java

public class Card {
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES; }

    public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, 
                       NINE, TEN, JACK, QUEEN, KING, ACE; }

    final Rank rank;
    final Suit suit;

    public Card (final Rank rank, final Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }
}    

2 个答案:

答案 0 :(得分:3)

您没有覆盖Card类中的toString()方法。因此,您使用Object类中的herited:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Card课程中覆盖它:

@Override
public String toString(){
    return suit.name()+"-"+rank.name();
}

答案 1 :(得分:1)

到您的Card类添加以下方法:

public String toString()
{
    return this.rank + " " + this.suit;
}