-5

我有一张卡片数组列表 ArrayList 手;假设手={2S,3H,2D,6H,4C}。我需要一种方法来对 arraylist 手进行排序,以便得到hand = {4C,2D,3H,6H,2S}. 我知道 enum 有一个方法compareTo(),但我不知道如何使用它。谁能给我一些指导?

public class PlayingCard implements Comparable
 {
//Instance Variables
private Suit suit;
private Rank rank;

//Constructor
public PlayingCard(Suit suit, Rank rank)
{
    this.suit = suit;
    this.rank = rank;
}
....
 public int compareTo(Object other)
 {
  PlayingCard that = (PlayingCard)other;

  if (this.suit == that.suit)
     return -this.rank.compareTo(((PlayingCard)other).rank);

  return -this.suit.compareTo(((PlayingCard)other).suit);         
 }

//============================================================================
 //Representation of the Suit of a Playing-Card
public enum Suit
{
    CLUBS('C'), DIAMONDS('D'), HEARTS('H'), SPADES('S');

    private char symbol;

    private Suit(char symbol)
    {
        this.symbol = symbol;
    }

    public char getSymbol()
    {
        return this.symbol;
    }
}

//============================================================================  
 //Representation of the Rank os a Playing-Card
public enum Rank
{
    DEUCE('2'), TREY('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'),
    EIGHT('8'), NINE('9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), ACE('A');

    private char symbol;

    private Rank(char symbol)
    {
        this.symbol = symbol;
    }

    public char getSymbol()
    {
        return this.symbol;
    }
}
}

--------------------------------------------------------------------------------------
public class PlayingCardHand {
//Instance Variables

private int cardsInCompleteHand;     //Maximum # cards in this hand
private ArrayList<PlayingCard> hand; //A hand of Playing-Cards
private Comparator comparer;         //Client-provided comparison of PlayingCards

//Constructor
//Appropriate when PlayingCard compareTo() is to be used to compare PlayingCards
public PlayingCardHand(int handSize) {

    if (handSize < 1) {
        throw new RuntimeException("Hand size cannot be less than 1");
    }
    cardsInCompleteHand = handSize;
    hand = new ArrayList<PlayingCard>();

}
...
public void sortCards() 
{
}
4

1 回答 1

3

您应该添加一个compareTo()方法,该方法Card首先按 排序Rank,如果Rank相等,则按Suit。如果我们使用Guava,这很简单:

public class Card implements Comparable<Card>
{
  private Rank rank;
  private Suit suit;

  ...

  public int compareTo(Card that) 
  {
    return ComparisonChain.start()
      .compare(this.rank, that.rank)
      .compare(this.suit, that.suit)
      .result();
  }
}

这是用于ComparisonChain.

如果我们假设一手牌List<Card>,那么您可以使用 对列表进行排序Collections.sort(hand)

于 2013-05-21T00:54:04.703 回答