可比类Java

时间:2012-11-07 14:31:59

标签: java class methods 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 + "."; 
}
}

1 个答案:

答案 0 :(得分: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));
}