0

I am new to Java and I am trying to work on my first project, it's a card game, called Taki, I created a card object that both the Deck and the Player classes use. Now, I want to sort the cards on the player "hand", I choose to use ArrayList for the cards, in both scenarios, but I am having trouble sorting the cards because I want to sort it first by the color and then by the number.

Here is the basic of the card class.

public class Card {
    private String name;
    private String color;
    private String number;


    public Card(String color, String number) {
        this.color = color;
        this.number = number;
    }

    public String getColor() {
        return color;
    }

    public String getNumber() {
        return number;
    }

    public String getName() {
        if (color.equals("White")) {
            name = getNumber();
        } else {
            name = getColor() + " " + getNumber();
        }
        return name;
    }

I saw this - Sort an ArrayList base on multiple attributes But all they did there is just handing out the solution, I want to know what to do, not just copy paste, so if someone could explain to me I would highly appreciate it.

elii236
  • 98
  • 4
  • The solution tells you what to do, you provide a custom `Comparator` object for the `sort()` method. – Progman Apr 22 '19 at 08:54
  • Your color should probably be an `enum` rather than a string if you want to sort by it and the order actually means anything - sorting by lexicographic order would mean that in different languages the game is played differently... Same goes for the name. Does it really mean anything if your "Stop" card comes before the "TAKI" card, just because "S" comes before "T"? – RealSkeptic Apr 22 '19 at 08:58
  • I was writing an answer, but the question was closed before I could submit it. You can create your comparator like this: `Comparator.comparing(Card::getColor).thenComparing(Card::getNumber);`. That definition should be pretty self explanatory. – marstran Apr 22 '19 at 08:59

0 Answers0