定义的Helper类:- package collectionsSort;
- import java.util.Collections;
- import java.util.List;
- public class Helper {
- /**
- * 从小到大排序
- * @param list
- */
- public static void small2Big(List<Integer> list) {
- Collections.sort(list);
- }
- /**
- * 从小到大排序
- * @param list
- */
- public static void big2Small(List<Integer> list) {
- IntComparator ic = new IntComparator();
- Collections.sort(list,ic);
- }
- }
复制代码 所要使用的比较器:- package collectionsSort;
- import java.util.Comparator;
- public class IntComparator implements Comparator<Integer> {
- @Override
- public int compare(Integer i1,Integer i2) {
- if(i1>i2)
- return -1;
- else if(i1==i2)
- return 0;
- return 1;
- }
- }
复制代码 集合排序测试类:- package collectionsSort;
- import java.util.ArrayList;
- import java.util.List;
- public class CollectionSort {
- public static void main(String[] args) {
- List<Integer> list = new ArrayList<Integer>();
- list.add(5);
- list.add(1);
- list.add(4);
- list.add(2);
- list.add(3);
- Helper.small2Big(list);
- System.out.println(list);
- System.out.println("--------------------淫荡的分割线-------------------------");
- Helper.big2Small(list);
- System.out.println(list);
- }
- }
复制代码 |