Previous | Next | Trail Map | Internationalization | Working with Text

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. The following table contains some sample calls to Collator.compare:

Example Return Value Explanation
myCollator.compare("abc", "def") -1 "abc" is less than "def"
myCollator.compare("rtf", "rtf") 0 the two strings are equal
myCollator.compare("xyz", "abc") 1 "xyz" is greater than "abc">

You 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. This program shows what can happen when you sort the same list of words with two different collators:

Collator fr_FRCollator = Collator.getInstance(new Locale("fr","FR"));
Collator en_USCollator = Collator.getInstance(new Locale("en","US"));
The 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 preceding list is in the wrong order. In French, "pêche" should follow "péché" in a sorted list. The French Collator sorts the array of words correctly:
peach
péché
pêche
sin


Previous | Next | Trail Map | Internationalization | Working with Text