码迷,mamicode.com
首页 > 编程语言 > 详细

List排序Collections.sort 重写compare

时间:2018-12-07 17:17:52      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:new   ati   main   排序   sys   com   return   before   tor   

 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表示逆序

List排序Collections.sort 重写compare

标签:new   ati   main   排序   sys   com   return   before   tor   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!