Comparator接口源码:
public interface Comparator<T> {
int compare(T var1, T var2);
}
Arrays.sort()方法需要传入一个数组,和一个实现Comparator接口类的实例。
如将学生数组按照分数进行排序:
// 定义学生类
class Student{
public int scores;
private String name;
public Student(String name, int scores){
this.name = name;
this.scores = scores;
}
}
比较器类:
// 定义继承Comparator接口的实现类
class com implements Comparator<Student>{
@Override
// 重写compare方法
public int compare(Student t1, Student t2) {
return t1.scores - t2.scores;
}
}
测试类:
public class studentTest {
public static void main(String[] args) {
Student[] students = new Student[2];
students[0] = new Student("小红",101);
students[1] = new Student("小明",100);
Arrays.sort(students, new com());
}
}
比较器也可写成匿名内部类的形式:
public class studentTest {
public static void main(String[] args) {
Student[] students = new Student[2];
students[0] = new Student("小红",101);
students[1] = new Student("小明",100);
Arrays.sort(students, new Comparator<Student>() {
@Override
// 重写compare方法
public int compare(Student t1, Student t2) {
return t1.scores - t2.scores;
}
});
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。