1. 比较器
遵守以下限制条件:自反性、对称性、传递性
注:强烈建议 ( x.compareTo(y) == 0 ) == ( x.equal(y) )
两种方式实现比较器:
a:实现Comparable<T>接口
b:实现Comparator<T>接口
public class CompareTest {
@Test
public void testCompare() {
Student a = new Student(1, "b");
Student b = new Student(2, "c");
Student c = new Student(2, "a");
List<Student> list = new ArrayList<>();
list.add(a);
list.add(b);
list.add(c);
//第一张方法排序
Collections.sort(list);
//第二种方法排序
Compare compare = new Compare();
Collections.sort(list, compare);
System.out.println(new Gson().toJson(list));
}
private class Student implements Comparable<Student> {
int code;
String name;
public Student(int code, String name) {
this.code = code;
this.name = name;
}
@Override
public int compareTo(Student o) {
if (this.code != o.code)
return this.code - o.code;
return o.name.compareTo(this.name);
}
}
private class Compare implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.code != s2.code)
return s1.code - s2.code;
return s1.name.compareTo(s2.name);
}
}
}
遵守以下限制条件:自反性、对称性、传递性
注:强烈建议 ( x.compareTo(y) == 0 ) == ( x.equal(y) )