Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a deck of cards by suit and then rank

I have this Java class:

class Card
{
    private Suit suit;
    private int  rank;
}

(Suit is an enum)

There are four suits with ranks 1-9 each and four suits with a single possible rank 0. Each card exists in an unknown but constant among all cards number of copies. How would I sort a deck in a set order of suits, and by increasing rank in each suit?

like image 282
Igor Avatar asked Dec 29 '22 02:12

Igor


1 Answers

You'll need to either

  1. implement the Comparable interface on the card object: add a compareTo function that determines whether another card should be before or after this one in the sort order
  2. implement a Comparator object that accepts two cards and indicates which order they should appear in

and then you can use Collections.sort on your list.

like image 114
Rup Avatar answered Dec 30 '22 16:12

Rup