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