[原創]Java中的字符串比較,按照使用習慣進行比較

java中的字符串比較通常能夠採用compareTo函數,若是a.compareTo(b)返回的是小於0的數,那麼說明a的unicode編碼值小於b的unicode編碼值。
可是不少狀況下,咱們開發一款app須要結合「國情」,好比在電話本中,咱們但願「李四」排在「zhangsan」的前面,可是若是採用普通的compareTo函數的字符串比較的方式,那麼「zhangsan」小於「李四」,由此形成了「zhangsan」的排序先於「李四」。
 
解決方式是採用java提供的 Collator類。
 
1、原理分析:
1 public abstract class Collator implements Comparator<Object>, Cloneable{}
Collator是一個抽象類,實現了Comparator和Clonable接口,Collator的構造方式有如下幾種:
 
1.
1 /**
2  * Returns a {@code Collator} instance which is appropriate for the user's default
3  * {@code Locale}.
4  * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
5  */
6 public static Collator getInstance() {
7     return getInstance(Locale.getDefault());
8 }

 

註釋中已經註明:返回一個按照用戶當地排序規則的Locale做爲參數,通常來講getDefault()獲取的Locale就會根據中國人的使用習慣進行比較。傳入getInstance(Locale)函數中,接着看此函數的實現:
 
2.
1 /**
2  * Returns a {@code Collator} instance which is appropriate for {@code locale}.
3  */
4 public static Collator getInstance(Locale locale) {
5     if (locale == null) {
6         throw new NullPointerException("locale == null");
7     }
8     return new RuleBasedCollator(new RuleBasedCollatorICU(locale));
9 }
函數生成一個RuleBasedCollator對象,此對象繼承了Collator抽象類
 
2、使用方法
1.工具類實現。
使用方法見下面我寫的工具類:
 
 1 public class CompareHelper {
 2 
 3    public static final Collator COLLATOR = Collator.getInstance();
 4 
 5    public static final Comparator<Contact> COMPARATOR_CONTACT;
 6    
 7    static
 8    {
 9       COMPARATOR_CONTACT = new Comparator<Contact>(){
10          public final int compare(Contact a, Contact b){
11             return COLLATOR.compare(a.sortKeyString, b.sortKeyString);
12          }
13       };
14    }
15    private CompareHelper(){}
16 }

2.對List元素進行從新排序:html

1 Collections.sort(contacts, CompareHelper.COMPARATOR_CONTACT);

 

3.針對兩個字符串進行「本地化」比較,使用的方法是:java

                int compareRet = CompareHelper.COLLATOR.compare(stringA, stringB);

不要使用String自帶的方法stringA.compareTo("stringB")。反之,當須要使用非「本地化」的比較方法時,須要使用的是stringA.compareTo("stringB")app

相關文章
相關標籤/搜索