|
|
Working with Text |
You use theCollatorclass to perform locale-independent comparisons. TheCollatorclass is locale-sensitive. To see which locales theCollatorclass supports, invoke thegetAvailableLocalesmethod:When you instantiate theLocale[] locales = Collator.getAvailableLocales();Collatorclass, you invoke thegetInstancemethod and specify the locale:TheCollator myCollator = Collator.getInstance(new Locale("en", "US"));getInstancemethod actually returns aRuleBasedCollator, which is a concrete subclass ofCollator. TheRuleBasedCollatorcontains 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 theRuleBasedCollator, your program won't need special routines to deal with the way collation rules vary with language.You invoke the
Collator.comparemethod to perform a locale-independent string comparison. Thecomparemethod 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 toCollator.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
comparemethod when performing sort operations. The sample program calledCollatorDemo.javauses thecomparemethod 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:The method for sorting, calledCollator fr_FRCollator = Collator.getInstance(new Locale("fr","FR")); Collator en_USCollator = Collator.getInstance(new Locale("en","US"));sortStrings, can be used with anyCollator. Notice that thesortStringsmethod invokes thecomparemethod:The Englishpublic 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; } } } }Collatorsorts the words as follows: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 Frenchpeach pêche péché sinCollatorsorts the array of words correctly:peach péché pêche sin
|
|
Working with Text |