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 ofString.compareTo
. "7" will come before "King", and "10" will come before "2".Sort will sort everything according to your charset. In otherwords, all numbers will come before letters in the lexicographic order. For example, decimal numbers start with a '.' and out of order lexicographically.
If you want to change this, make Comparator object. You could then put the items in whatever order you like.
For example, this will sort numbers in numerical order, and also words in lexical order:
PS not tested!
As @Jon Skeet said, the built-in sort will compare based on Unicode values. You'd have to write your own sorting method.
As long as you're writing your own code, though, might I suggest an enumeration? A deck of cards is one of the canonical examples for use of enums. The short version is that you can declare your own sort order for a group of things; you could even make the king of spades outrank the king of diamonds, if you wanted. Check out Sun's tutorial here.
If the string is a number it is already being sorted ( as an String though ) look:
Prints
Is that what you need?
edit
Assuming ( guessing ) what you need is to sort a deck of cards, which have both numbers and "letters" ( J, Q, K, A ) you may try to use a custom comparator.
Here's one that takes into consideration the numbers "as numbers" the the rest as strings, so "10" comes after "2" but before "Kings"
If that's what you need I guess this would help you to figure out the rest. Probably the next thing would be how to sort spades vs. hearts.
Following the answer by Roman you could create a class and implement the Comparable interface:
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:
and after that create instances in this manner:
After that it'll be much easier to make all operations with cards (and sorting particularly) using field
value
instead of cards' names.