您的位置:首页 > 其它

List<String> 调用Collection.sort()整个流程的知识点

2017-12-01 23:45 281 查看

1.sort()本身:

Collection.sort()方法有两种形式,

格式一: public static

2.Comparator接口:

这个接口中最重要的方法实现就是compareTo(),这也是排序的关键,举个例子(String 中实现的compareTo()方法):

/* @param   anotherString   the <code>String</code> to be compared.
* @return  the value <code>0</code> if the argument string is equal to
*          this string; a value less than <code>0</code> if this string
*          is lexicographically less than the string argument; and a
*          value greater than <code>0</code> if this string is
*          lexicographically greater than the string argument.
*/
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;

int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}


由源码可以看出:

首先取出两个字符串的长度,比较较小的长度内,两者是否相等。

若不相等,则直接返回该位置字符的ASCII码相减后的值。

若各位置都相等,则将两个字符串长度的差值返回。

ps:之前我一直把compareTo和Comparator搞混,其实很好区分Comparator是一个接口,compareTo()是它的实现方法;

3.List<String>排序有什么用:

主要是用来判断每个字符出现的次数,因为排序之后整个字符串会变得很规整,使用indexOf()和lastIndexOf()就能很快的算出一个字符在String中出现的次数。

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: