public class TestComparator {
public static void main(String[] args) {
List<Integer> listnum = new ArrayList<Integer>();
listnum.add(1);
listnum.add(2);
listnum.add(3);
listnum.add(4);
listnum.add(5);
System.out.println("升序排序测试:");
Comparator<Integer> ascComparator = new NumComparator();//NumComparator自定义的另外一个类,用来判断两数之间的大小
Collections.sort(listnum, ascComparator);
for (int i = 0; i < listnum.size(); i++) {
System.out.print(listnum.get(i) + " ");
}
System.out.println("\n降序排序测试:");
Comparator<Integer> descComparator = Collections.reverseOrder(ascComparator);
Collections.sort(listnum, descComparator);
for (int i = 0; i < listnum.size(); i++) {
System.out.print(listnum.get(i) + " ");
}
}
}
class NumComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
结果:
升序排序测试:
1 2 3 4 5
降序排序测试:
5 4 3 2 1 |
|