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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM