1 public static <T> void sort(List<T> list, Comparator<? super T> c) {
2 list.sort(c);
3 }
4
5
6 @SuppressWarnings({"rawtypes", "unchecked"})
7 private static void mergeSort(Object[] src,
8 Object[] dest,
9 int low, int high, int off,
10 Comparator c) {
11 int length = high - low;
12
13 // Insertion sort on smallest arrays
14 if (length < INSERTIONSORT_THRESHOLD) {
15 for (int i=low; i<high; i++)
16 for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
17 swap(dest, j, j-1);
18 return;
19 }
20
21 public class ReplyComparator implements Comparator<Reply> {
22 @Override
23 public int compare(Reply o1, Reply o2) {
24 if(isAllNumber(o1.getContent()) && isAllNumber(o2.getContent())){
25 return Integer.valueOf(o1.getContent()).compareTo(Integer.valueOf(o2.getContent()));
26 }
27 return o1.getContent().compareTo(o2.getContent());
28 }
29
30 private boolean isAllNumber(String content){
31 String regex = "^[0-9]*$";
32 Pattern pattern = Pattern.compile(regex);
33 Matcher matcher = pattern.matcher(content);
34 if(matcher.matches()){
35 return true;
36 }
37 return false;
38 }
39 }
40
41
42 Collections.sort(result,new ReplyComparator());
對result 排序,Comparator接口的compare方法參數: Reply o1, Reply o2 01代表index = x 的對象, 02是index = x+1;
這個方法返回正數,則會交換o1,o2的位置,<=0時,則不會交換。
mergeSort 是Collections.sort方法內部調用的Arrays類的方法,第16行的條件 c.compare(dest[j-1], dest[j])>0可知
只有Comparator接口的compare方法返回正數,才會交換o1,o2的位置(o1的索引小於o2的索引),如果不希望交換位置,則返回負數或0。
也就是說要想從大到小排序判定條件 if(o1>o2)【可為o對象某個屬性的比較】 return -1(小於等於0);
要想從小到大排序 if(o1>o2) return 1(大於0);
String.compareTo(String anotherString)
String a = "abc";
String b = "abcde"
a.compareTo(b) 返回 a.lenth -b.lenth 也就是b大
String a = "bac";
String b = "abc";
a.compareTo(b) 返回 ‘b’ -'a' (>0 ) 也就是a大
a.compareTo(b) 返回正數 則a大, 返回負數,a小,返回0相等