Previous | Next | Trail Map | Internationalization | Comparing Strings

Performing Locale-independent Comparisons

You use the Collator class to perform locale-independent comparisons. The Collator class is locale-sensitive. To see which locales the Collator class supports, invoke the getAvailableLocales method:
Locale[] locales = Collator.getAvailableLocales();
When you instantiate the Collator class, you invoke the getInstance method and specify the locale:
Collator myCollator = Collator.getInstance(new Locale("en", "US"));
The getInstance method actually returns a RuleBasedCollator, which is a concrete subclass of Collator. The RuleBasedCollator contains a set of rules that determine the sort order of strings for the locale you specify. These rules are predefined for each locale. Because the rules are encapsulated within the RuleBasedCollator, your program won't need special routines to deal with the way collation rules vary with language.

You invoke the Collator.compare method to perform a locale-independent string comparison. The compare method returns an integer less than, equal to, or greater than zero when the first string argument is less than, equal to, or greater than the second string argument. We demonstrate this in the code that follows:

System.out.println(myCollator.compare("abc", "def"));
System.out.println(myCollator.compare("rtf", "rtf"));
System.out.println(myCollator.compare("xyz", "abc"));
The output generated by the preceeding lines of code is:
-1
0
1
You'll want to use the compare method when performing sort operations. The sample program called CollatorDemo.java uses the compare method to sort an array of English and French words. In this program, we'll see what happens when we sort the same array with two different collators:
Collator fr_FRCollator = Collator.getInstance(new Locale("fr","FR"));
Collator en_USCollator = Collator.getInstance(new Locale("en","US"));
Our method for sorting, called sortStrings, can be used with any Collator. Notice that the sortStrings method invokes the compare method:
public static void sortStrings(Collator collator, String[] words) {
    String tmp;
    for (int i = 0; i < words.length; i++) {
        for (int j = i + 1; j < words.length; j++) {
            // Compare elements of the array two at a time.
            if (collator.compare(words[i], words[j] ) > 0 ) {
                // Swap words[i] and words[j]
                tmp = words[i];
                words[i] = words[j];
                words[j] = tmp;
            }
        }
    }
}
The English Collator sorts the words as follows:
peach
pêche
péché
sin
According to the collation rules of the French language, the preceeding list is in the wrong order. In French, "pêche" should follow "péché" in a sorted list. Our French Collator sorts the array of words correctly:
peach
péché
pêche
sin


Previous | Next | Trail Map | Internationalization | Comparing Strings