I am trying to sort an ArrayList of Strings that represent card values. So, some cards contain letters ("King") and some contain Strings containing only a number ("7"). I know to use Collections.sort, but it only sorts Strings that contain letters. How do I get the ArrayList to be sorted by number as well as alphabetically?
Edit: Sorry, I must not have been paying much attention when I looked at the sorting. The sort works correctly, I must have just been thrown off by the fact that a 10 will come before a 2. Thanks
No, Collections.sort
will sort everything, using an Unicode ordinal lexicographic comparison as that's the behaviour of String.compareTo
. "7" will come before "King", and "10" will come before "2".
As I understand, you have an array like ["7", "Queen", "9", "6"]
and you want it to look like ["Queen", "9", "7", "6"]
(or in reverse order) after sorting is done.
I'd recommend to make it a bit more object-oriented i.e. create class Card with fields name and value:
class Card {
private final String name;
private final int value;
...
//constructor and getters
}
and after that create instances in this manner:
Card six = new Card("6", 6);
Card ten = new Card("10", 10);
Card queen = new Card("Queen", 12);
After that it'll be much easier to make all operations with cards (and sorting particularly) using field value
instead of cards' names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With