Let me give you an example for what i'm trying to achieve. Look only to the numbers because it's a card game.
I have:
harten5 klaveren4 klaveren7 schoppen5 ruiten5 schoppen2 klaverenheer schoppenheer schoppendame schoppen6 klaverenboer schoppen8 ruitenheer klaveren6...
I want to sort this on the value to:
schoppen2 harten2 ruiten2 klaveren2 ruiten3 harten3 schoppen3 klaveren3 klaveren4 harten4 schoppen4 ruiten4 harten5 schoppen5 ruiten5...
But i get the 10 before the 2 like this:
schoppen10 ruiten10 harten10 klaveren10 schoppen2 harten2 ruiten2 klaveren2 ruiten3 harten3 schoppen3 klaveren3...
This is my basic compareTo Method:
@Override
public int compareTo(Card p) {
return this.value.compareTo(p.value);
}
Because String
's (I guess this.value
is String
) compareTo
compares lexicographically, whilst you want numerically. So you have to reimplement it, take substring (or find the last part which is a digit, convert it to Integer
and then user compareTo
on that Integer
.
In general, I think your class Card could be improved a bit. In particular, I would rewrite it:
class Card {
private String value;
private Integer rank;
...
public int compareTo(Card c) {
// Additional logic if you need to consider
// also value (suite) in comparison
return this.rank.compareTo(c.rank);
}
}
But you can also use an enum
for this purpose.