Comparator在jdk7前是megesort,jdk7之后是Timsort,看下面连接 http://blog.sina.com.cn/s/blog_8e6f1b330101h7fa.html
代码语言:javascript复制package Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Text {
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
a.add(5);
a.add(7);
a.add(4);
Collections.sort(a, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
System.out.println(a "比" b);
return a - b;
}
});
System.out.println(a);
}
}
输出:
代码语言:javascript复制7比5
4比7
4比7
4比5
[4, 5, 7]
当把return b-a时:
代码语言:javascript复制package Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Text {
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
a.add(5);
a.add(7);
a.add(4);
Collections.sort(a, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
System.out.println(a "比" b);
return b - a;
}
});
System.out.println(a);
}
}
输出:
代码语言:javascript复制7比5
4比7
4比5
[7, 5, 4]
总结: 升序:a-b 降序:b-a 也可以 升序用 return a>=b?1:-1; 降序用:return a>=b?-1:1;