两者都是比较接口
void sort(List<Comparable>);
Sorts the specified list in ascending natural order. The algorithm is stable which means equal elements don't get reordered.
void sort(List<Object>, Comparator<? super Object>);
Sorts the specified list using the specified comparator. The algorithm is stable which means equal elements don't get reordered.
Comparable:比较的List集合中的对象,本身就继承Comparable,eg:Integer Double等,且按自然排序(默认从小到大)
Comparator:List对象中的集合没有继承Comparable或者自然排序不能满足程序要求,eg:从大到小、按字符串长短等自定义排序
Comparator 实现代码:
Comparator<?> com = new Comparator<?>(){
public int compare(? obj1, ? obj2){
return obj1.compareTo(obj2);
}
}
//解释代码:<?>表示泛型, 可以是复杂数据类型。重写的compare(? obj1, ? obj2)表示比较规则,此方法根据返回值来确定比较规则。如果obj1小于obj2则返回负数,则按从小到大自然排序;如果obj1等于obj2则返回0,此时两者顺序与原来顺序不变;如果obj1大于obj2则返回正数,则按从大到小排序。
总结:要实现按某一个对象的某一个值来排序List集合,则用Collections.sort(List<Object>, Comparator<? super Object>);方法,若想让整个集合从小到大排序,则return obj1.compareTo(obj2);若想让整个集合从大到小排序,则return obj1.compareTo(obj2) * -1;