1

我有这个类使用枚举类型作为甲板。使此类 Comparable 将卡片按升序排序的最有效方法是什么?如果它们是枚举类型,是否可以在一个方法中比较两个卡面值?(例如返回差异或什么?)谢谢。

public class Card {

public enum Rank {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, 
                    JACK, QUEEN, KING}
public enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}

private final Rank rank; 
private final Suit suit; 

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

public int compareTo(Card c) {
    Card aCard = (Card)c;
    int rankComparison = rank.compareTo(aCard.rank);
    return rankComparison != 0 ? rankComparison : suit.compareTo(aCard.suit);
}

public Rank rank(){
    return rank; 
}
public Suit suit(){
    return suit; 
}

public String toString(){ 
    return "The " + rank + " of " + suit + "."; 
}
}
4

1 回答 1

2
public int compareTo(Card c) {
    int rankComparison = rank.compareTo(c.rank);
    return rankComparison != 0 ? rankComparison : suit.compareTo(c.suit);
}

试试这个,只是让类实现Comparable接口。请注意,枚举是按照它们声明的顺序进行比较的。

见, http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html#compareTo (E )

要对此进行测试,您可以使用不同的卡编写 JUnit 测试,例如,

@Test
public void test()
{
    Card aceOfSpades = new Card(Rank.ACE, Suit.SPADES);
    Card fourOfClubs = new Card(Rank.FOUR, Suit.CLUBS);

    assertTrue(aceOfSpades.compareTo(fourOfClubs) > 0));
}
于 2012-11-07T14:37:20.533 回答