Search code examples
javaclassmethodscomparable

Comparable Class Java


I have this class using enum types for a deck. What would be the most efficient way to make this class Comparable to sort the cards into ascending order? Also is it possible to compare two card face values in a method if they are enum types? (for example return the difference or something?) Thanks.

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 + "."; 
}
}

Solution

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

    Try this, just make the class implement the Comparable interface. Be aware that enums are compared in the order they are declared.

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

    To test this you can write JUnit tests with different cards, for example,

    @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));
    }