zoukankan      html  css  js  c++  java
  • [原创]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")

  • 相关阅读:
    Why use strong named assemblies?
    Dependency Walker
    “等一下,我碰!”——常见的2D碰撞检测
    MOBA游戏的网络同步技术
    VS2017如何配置openGL环境
    UE4关于Oculus Rift (VR)开发忠告
    UE4 的json读写方式
    Blueprint 编译概述
    UE4编码规范
    Unreal Enginer4特性介绍
  • 原文地址:https://www.cnblogs.com/carbs/p/5312462.html
Copyright © 2011-2022 走看看