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
相关文章推荐
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序
- .NET中string[]数组和List<string>泛型的相互转换以及Array类的Sort()方法(转)
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- java 调用 c# webservice 压缩 List<string>示例
- Mybatis--查询collection--List<String>
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序(一)
- .NET中string[]数组和List<string>泛型的相互转换以及Array类的Sort()方法 【整理】
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- C# List<T>.Sort排序
- List<Map<String,Object>>取值知识点
- List<String>转换成CharSequence[]
- 读取文件内容返回List<String>类型
- String 数组 转成 List<String>
- List<T>和ObservableCollection<T>的相互转化
- C#中List<T>的排序用法(Sort)
- List<T>的Sort方法巧用
- 关于List.addAll(Collection<E>)方法遇到的问题
- C#中string[]数组和list<string>泛型的相互转换 【转】
- WebApi后端的List<String>前端如何发送?
- SilverLight的List<T>、ObservableCollection<T>和INotifyPropertyChanged的异同 (转)