List排序Collections.sort 重写compare

 1 static List<Integer> intList = Arrays.asList(2,5,7, 3, 1);
 2 
 3       public static void main(String[] args) { 
 4           
 5           System.out.println("before sort:");
 6             PrintUtil.showList(intList);
 7             System.out.println("=========================");
 8             Collections.sort(intList,new Comparator<Integer>() {
 9 
10                 public int compare(Integer o1, Integer o2) {
11                     // 返回值为int类型,大于0表示正序,小于0表示逆序
12                     System.out.println("o2-o1:"+(o2-o1)+"========o2="+o2+"o1="+o1);
13                     if(o2>o1){
14                         return -1;    
15                     }else{
16                         return 1;    
17                     }
18                 }
19             });
20             System.out.println("after sort:");
21             PrintUtil.showList(intList);
22           
23     }

根据需求排序,方法内比较两个对象的参数哪个优先,返回值为int类型,大于0表示正序,小于0表示逆序

原文地址:https://www.cnblogs.com/locker777/p/10083886.html