1. 程式人生 > >List排序Collections.sort 重寫compare

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