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

来源:互联网 发布:java 包装类 编辑:程序博客网 时间:2024/06/08 08:32

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中出现的次数。

阅读全文
0 0
原创粉丝点击