String comparisons in Java can generally take the compareTo function, and if A.compareto (b) Returns a number less than 0, then the Unicode encoding value of a is less than the Unicode encoded value of B. However, in many cases, we need to develop an app to combine "national conditions", such as in the phone book, we Want "John Doe" in front of "Zhangsan", but if the normal CompareTo function of the string comparison, then "Zhangsan" less than "John Doe", This results in a sort of "Zhangsan" prior to "John Doe". The workaround is to use the Collator class provided by Java. First, the principle analysis:
1 Public Abstract class Implements Comparator<object>, cloneable{}
Collator is an abstract class that implements the comparator and clonable interfaces, and the collator is constructed in the following ways: 1.
1 /**2 * Returns a {@codeCollator} instance which is appropriate for the user ' s default3 * {@codeLocale}.4 * See "<a href=". /util/locale.html#default_locale ">be wary of the default locale</a>".5 */6 Public StaticCollator getinstance () {7 returngetinstance (Locale.getdefault ());8}
It is noted in the comments that the locale used by the user's local collation is returned as a parameter, and the locales obtained by Getdefault () are generally compared according to the Chinese usage habits. In the getinstance (Locale) function, look at the implementation of this function: 2.
1 /**2 * Returns a {@codeCollator} instance which is appropriate for {@codelocale}.3 */4 Public StaticCollator getinstance (locale locale) {5 if(Locale = =NULL) {6 Throw NewNullPointerException ("locale = = NULL");7 }8 return NewRuleBasedCollator (NewRulebasedcollatoricu (locale));9}
The RuleBasedCollator function generates an object that inherits the Collator abstract class two, using Method 1. Tool class implementation. See the tool Class I wrote below:
1 Public classComparehelper {2 3 Public Static FinalCollator Collator =collator.getinstance ();4 5 Public Static FinalComparator<contact>comparator_contact;6 7 Static8 {9Comparator_contact =NewComparator<contact>(){Ten Public Final intCompare (Contact a, contact B) { One returnCollator.compare (a.sortkeystring, b.sortkeystring); A } - }; - } the PrivateComparehelper () {} -}
2. Reorder the list elements:
1 collections.sort (contacts, comparehelper.comparator_contact);
String comparisons in Java, which are compared according to usage habits