To answer the question about compareTo
: a.compareTo(b)
should return something negative if a
is less than b
, positive if a
is greater than b
, and 0 if they're equal. Also, if you're ordering the objects, one of the rules the ordering should follow is that if a.compareTo(b) < 0
, then b.compareTo(a) > 0
. (You can't have both "a
is less than b
" and "b
is less than a
"). Your compareTo
, which just returns -1
anytime the cards aren't equal, doesn't follow this rule. To fix this, you'll need to decide on the ordering. What does a "sorted deck" look like? Probably all the clubs are together, followed by all the diamonds, etc., which means that any club card will be less than any diamond card. To do this correctly, you'll need to compare the suits first, and the ranks only if the suits are equal:
public int compareTo (Card aCard){
int suitCompare = this.aSuit.compareTo(aCard.aSuit);
if (suitCompare != 0) {
return suitCompare;
}
return this.aNumeral.compareTo(aCard.aNumeral);
}
The compareTo
on each enum
will return <0
, 0
, or >0
. So you can compare the suits, return a value that is <0
or >0
, and then compare the ranks if the suits are equal. This is the general approach for writing any compareTo
method where multiple pieces of data need to be checked.