Working with Text |
You use theCollator
class to perform locale-independent comparisons. TheCollator
class is locale-sensitive. To see which locales theCollator
class supports, invoke thegetAvailableLocales
method:When you instantiate theLocale[] locales = Collator.getAvailableLocales();Collator
class, you invoke thegetInstance
method and specify the locale:TheCollator myCollator = Collator.getInstance(new Locale("en", "US"));getInstance
method actually returns aRuleBasedCollator
, which is a concrete subclass ofCollator
. TheRuleBasedCollator
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 theRuleBasedCollator
, 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. Thecompare
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 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
compare
method when performing sort operations. The sample program calledCollatorDemo.java
uses thecompare
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: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 thesortStrings
method invokes thecompare
method: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; } } } }Collator
sorts 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é sinCollator
sorts the array of words correctly:peach péché pêche sin
Working with Text |