comparator 字符串比较大小_Comparator 和 Comparable 比较

Comparator 是一个比较器,而Comparable是支持排序的一个标识,如果某一个类实现了Comparable则表示类支持排序,且排序方式为‘接口提供’。

Comparator是一个比较器, 相当与一个自定义的比较方式,所以不能运用在通用工具中,一般地, 我们使用比较器来比较两个对象的时候,需要借用外部力量,比如内部类实现Comparator,提供compare方法实现。

当我们在后期才会考虑到该类对象需要排序的时候,那么我们可以考虑使用Comparator 自定义个比较器,然后达到排序的目的, 比如String 的忽略大小写比较字符串.

/**

* A Comparator that orders String objects as by

* compareToIgnoreCase. This comparator is serializable.

*

* Note that this Comparator does not take locale into account,

* and will result in an unsatisfactory ordering for certain locales.

* The java.text package provides Collators to allow

* locale-sensitive ordering.

*

* @see java.text.Collator#compare(String, String)

* @since 1.2

*/

public static final Comparator CASE_INSENSITIVE_ORDER

= new CaseInsensitiveComparator();

private static class CaseInsensitiveComparator

implements Comparator, java.io.Serializable {

// use serialVersionUID from JDK 1.2.2 for interoperability

private static final long serialVersionUID = 8575799808933029326L;

public int compare(String s1, String s2) {

int n1=s1.length(), n2=s2.length();

for (int i1=0, i2=0; i1

char c1 = s1.charAt(i1);

char c2 = s2.charAt(i2);

if (c1 != c2) {

c1 = Character.toUpperCase(c1);

c2 = Character.toUpperCase(c2);

if (c1 != c2) {

c1 = Character.toLowerCase(c1);

c2 = Character.toLowerCase(c2);

if (c1 != c2) {

return c1 - c2;

}

}

}

}

return n1 - n2;

}

}

//called

/**

* Compares two strings lexicographically, ignoring case

* differences. This method returns an integer whose sign is that of

* calling compareTo with normalized versions of the strings

* where case differences have been eliminated by calling

* Character.toLowerCase(Character.toUpperCase(character)) on

* each character.

*

* Note that this method does not take locale into account,

* and will result in an unsatisfactory ordering for certain locales.

* The java.text package provides collators to allow

* locale-sensitive ordering.

*

* @param str the String to be compared.

* @return a negative integer, zero, or a positive integer as the

* specified String is greater than, equal to, or less

* than this String, ignoring case considerations.

* @see java.text.Collator#compare(String, String)

* @since 1.2

*/

public int compareToIgnoreCase(String str) {

return CASE_INSENSITIVE_ORDER.compare(this, str);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值