Java中的字符串比较,按照使用习惯进行比较

来源:互联网 发布:得力3960考勤机软件 编辑:程序博客网 时间:2024/05/29 19:11

http://www.cnblogs.com/carbs/p/5312462.html这是原文地址,如有侵权联系我立刻删除!!

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 default3  * {@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")


原创粉丝点击