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


java中的字符串比較一般可以采用compareTo函數,如果a.compareTo(b)返回的是小於0的數,那么說明a的unicode編碼值小於b的unicode編碼值。
但是很多情況下,我們開發一款app需要結合“國情”,比如在電話本中,我們希望“李四”排在“zhangsan”的前面,但是如果采用普通的compareTo函數的字符串比較的方式,那么“zhangsan”小於“李四”,由此造成了“zhangsan”的排序先於“李四”。
 
解決方式是采用java提供的 Collator類。
 
一、原理分析:
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抽象類
 
二、使用方法
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元素進行重新排序:

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

 

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

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

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

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM