I'm creating a Java
program that simulates a game of Hearts. I have a Card
class that I created for another card game simulation:
public abstract class Card implements Comparable<Card>{
public enum Suits {
SPADES,
CLUBS,
HEARTS,
DIAMONDS
}
public enum Values {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE,
}
private Suits suit;
private Values value;
public Card(final Values value, final Suits suit) {
this.value = value;
this.suit = suit;
}
public Values getValue() {
return value;
}
public Suits getSuit() {
return suit;
}
public void showCard() {
value = getValue();
suit = getSuit();
System.out.println(value + " of " + suit);
}
private int compareTo(final Card comparedToCard) {
//code here
}
}
I need some assistance implementing the compareTo
method. I have experience using this method, and how it should return 1, 0, or -1 based on how you want to compare you objects. However, I have never implemented it using enums
before. I know the Enum
class implements comparable but even after looking at API documentation I don't know how to compare two enums.
My desired result would be to sort an ArrayList<Card>
in such a way that they would be sorted first by Suit
: Club -> Diamond -> Spade -> Heart, and to also have them sorted by Value
so: Club(2->Ace), Diamond(2->Ace), ect...
Any help would be much appreciated
Enums have a natural order, so compare by the suit property and then by the value:
Or if you want a comparator: