Sorting a deck of cards by suit and then rank

11,539

Solution 1

Have a look at implementing Comparable on the enum.

Solution 2

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.

Solution 3

Make Rank an enum too and you can deal a sorted deck as such:

    for (Suit suit : Suit.values())
        for (Rank rank : Rank.values())
            deck.add(new Card(rank, suit));

Solution 4

make it implement the Comparable interface. Theres only only one method you'll need to write. Then they can be compared to each other, and you have a number of existing sort options, such as static Arrays.sort if you have an array or Collections.sort if its any kind of Collection (List, Vector, etc)

Besides implementing on Card you might have to do the same for Suit depending on how its done.

Share:
11,539
Igor
Author by

Igor

Updated on July 20, 2022

Comments

  • Igor
    Igor almost 2 years

    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?