2013-05-21 49 views
-5

我有一個數組列表ArrayList的arraylist;假設手= {2S,3H,2D,6H,4C}。我需要一種方法來排列數組列表手,以便獲得hand = {4C,2D,3H,6H,2S}。我知道枚舉有一個方法compareTo(),但我不知道如何使用它。任何人都可以給我一些指導嗎?如何使用枚舉類型對arraylist進行排序

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() 
{ 
} 
+1

你有代表卡的對象嗎?您只向我們展示了代表卡片組件的兩個枚舉。 –

+0

是的,我有代表卡 – jorgeAChacon

+0

@ user1166061的對象,你能告訴我們代碼嗎? – mre

回答

3

您應該通過其第一Rank排序Card添加compareTo()方法,如果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的Javadoc。

如果我們假設List<Card>,那麼您可以使用Collections.sort(hand)對列表進行排序。

+0

我很抱歉沒有發佈整個代碼。是的手是Arraylist ,我需要使用Collections.sort(手) – jorgeAChacon

+0

@ user1166061對手進行排序:這是否回答了您的問題?如果是這樣,你應該把你的問題標記爲已回答。 –

+0

不,它沒有。我發佈了其餘的代碼,看看是否有人可以幫我想出一種方法來編寫排序方法。 – jorgeAChacon