List<Student> students = Lists.newArrayList(new Student("name1", 12), new Student("name2", 13));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(students);
打印出来的结果:
[Student{name='name1', age=12}, Student{name='name2', age=13}]
是怎么判定的呢?
追溯到Arrays的源码:
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
发现是compare()中,返回的是正数则两个调换位置. o1-o2>0 --> o1大 -->调换位置. 所以表现得是升序.
记录一下,以后再比较时就不会犯糊涂了.