|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Collation rules define the sort sequence of strings. These rules vary with locale, because various natural languages sort words differently. You can use the predefined collation rules provided by theCollatorclass to sort strings in a locale-independent manner.To instantiate the
Collatorclass invoke thegetInstancemethod. Usually, you create aCollatorfor the defaultLocale, as in the following example:You can also specify a particularCollator myDefaultCollator = Collator.getInstance();Localewhen you create aCollator, as follows:Collator myFrenchCollator = Collator.getInstance(Locale.FRENCH);The
getInstancemethod 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:
Collator.compareExamplesExample Return Value Explanation myCollator.compare("abc", "def")-1"abc"is less than "def"myCollator.compare("rtf", "rtf")0the 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 calledCollatorDemouses the
comparemethod 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 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++) { if (collator.compare(words[i], words[j]) > 0) { tmp = words[i]; words[i] = words[j]; words[j] = tmp; } } } }Collatorsorts the words as follows:peach péché pêche sinAccording to the collation rules of the French language, the preceding list is in the wrong order. In French péché should follow pêche in a sorted list. The French
Collatorsorts the array of words correctly, as follows:peach pêche péché sin
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.