简体   繁体   中英

Sorting of Strings using collections.sort() method

As per the documentation : This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array

Given the program below, I am not able to understand the sorting as how internally jvm judges that letter 'A' is smaller or bigger than letter 'a' ? As this is a string, the letters won't be assumed in ascii value so how the sorting happens?

public class LetterASort {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList();
        strings.add("aAaA");
        strings.add("AaA");
        strings.add("aAa");
        strings.add("AAaa");
        Collections.sort(strings);
        for (String s : strings) 
        { 
        System.out.print(s + " "); //prints AAaa AaA aAa aAaA 
        }
    }
}

Also I tried debugging the code which created a new doubt for me: the length of array turned out to be 4 rather than 3 as collections.sort is included in the length

The "natural ordering" that Collections.sort refers to is the one specified by Comparable -- which String implements, and which defines only one method, compareTo . So, the answer is in the definition of String.compareTo . Its documentation states:

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.

Lexicographical ordering basically means dictionary ordering. Essentially, order each letter alphabetically as far as you go, but if you're still tied when either word runs out of letters, then the shorter word goes first.

Unicode is the numerical value that each character has. There's a great introductory post about it here (it's not short, but it does a good job of walking you through not just what unicode is, but why it exists).

String class implements the Comparable interface. When sort happens, compareTo(String) method is called. For more look at the implementation of compareTo(String) method in String class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM