大家注意了,笔试时经常使用Java7,list并没有sort方法,请使用Collections.sort()
总结:
- 使用Collections.sort()传入ArrayList,会采用默认的方式进行排序(字典序)
- 使用Collections.sort()传入ArrayList和自己实现Commparator接口的类的对象,实现自定义排序
- 使用List.sort()传入自己实现Commparator接口的类的对象,实现自定义排序
- Comparator返回值在jdk1.7、jdk1.8里必须是一对相反数,如1和-1,不能是1和0.因为1.7的排序算法采用timsort,对返回值有严格要求http://baike.baidu.com/link?url=UCowuf65GHz3cWVf_d7t0QzYUCcwU0QUwserNTIrImlaTBvBAaVfywzppQ70DqWKzUu3dPqsF21k9IDpT8QPE_
测试代码:
import java.util.*;
public class TestArrayListSort {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
List listInt = new ArrayList(),
listStr = new ArrayList();
//自定义Comparator对象,自定义排序
Comparator c = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if((int)o1<(int)o2)
return 1;
//注意!!返回值必须是一对相反数,否则无效。jdk1.7以后就是这样。
// else return 0; //无效
else return -1;
}
};
listInt.add(2); listInt.add(4); listInt.add(9); listInt.add(5);
listStr.add("haha");
listStr.add("hehe");
listStr.add("ao");
listStr.add("Ti");
@SuppressWarnings("rawtypes")
List list01 = new ArrayList(listInt);
List list02 = new ArrayList(listInt);
Collections.sort(listInt);
Collections.sort(listStr);
list01.sort(c);
Collections.sort(list02,c);
System.out.println(listInt);
System.out.println(listStr);
System.out.println(list01);
System.out.println(list02);
}
}
输出:
[2, 4, 5, 9]
[Ti, ao, haha, hehe]
[9, 5, 4, 2]
[9, 5, 4, 2]
[Ti, ao, haha, hehe]
[9, 5, 4, 2]
[9, 5, 4, 2]