以外部比较器为例,如下图:o1在o2的后面,如:o1是s2,o2是s1;o1是s3,o2是s2。(此顺序是源码比较顺序),然后返回负数会继续循环至非负数,负数那一段会交换;正数就不用管。源码部分如图2,c.compare方法就是自己重写的方法,对图1来说就是重写的对Student排序的方法,然后lo值为0,runHi为1。所以,o1-o2是升序:因为后面的数减前面的数小于0即后面的小于前面的,交换,就相当于把小的放前面即升序。
图1:外部比较器示例图
List<Student> list = new ArrayList<>();
Student s1 = new Student("shallow",25);
Student s2 = new Student("feather",23);
Student s3 = new Student("lll",22);
Collections.addAll(list,s1,s2,s3); //collections工具类
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 升序
return o1.getAge() -o2.getAge();
}
});
图2:jdk源码
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}