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?
If the string is a number it is already being sorted ( as an String though ) look:
import java.util.*;
class Sort {
public static void main( String [] args ) {
List list = Arrays.asList("Kings","7", "Abcd", "3.1416");
Collections.sort( list );
System.out.println( list );
}
}
Prints
$ java Sort
[3.1416, 7, Abcd, Kings]
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"
import java.util.*;
class Sort {
public static void main( String [] args ) {
List<String> list = Arrays.asList("Kings","7", "Queen", "3", "10", "A", "2", "8", "Joker");
Collections.sort( list , new Comparator<String>(){
public int compare( String a, String b ){
// if both are numbers
if( a.matches("\\d+") && b.matches("\\d+")) {
return new Integer( a ) - new Integer( b );
}
// else, compare normally.
return a.compareTo( b );
}
});
System.out.println( list );
}
}
$ java Sort
[2, 3, 7, 8, 10, A, Joker, Kings, Queen]
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:
class Card implements Comparable<Card> {
public int compareTo( Card other ) {
// add custom logic to compare one card with other
}
}