public class Student {
public static final Comparator<Student> BY_NAME = new ByName();
public static final Comparator<Student> BY_Gpa = new ByGpa();
private static class ByName implements Comparator<Student> {
public int compare(Student v, Student w) {
return v.getName().compareTo(w.getName());
}
}
private static class ByGpa implements Comparator<Student> {
public int compare(Student v, Student w) {
if (v.getGpa() == w.getGpa()) return 0;
else if (v.getGpa() < w.getGpa()) return -1;
else return 1;
}
}
}
我不明白Collection.sort
。为什么必须使用这样复杂的形式?为什么不是像C ++这样的类中的静态函数进行排序,而不是返回一个实现具有方法比较的Comparator的类?这太复杂了。
答案 0 :(得分:2)
Java 8对Comparator
界面的增强使其更加优雅:
public static final Comparator<Student> BY_NAME = Comparator.comparing(Student::getName);
public static final Comparator<Student> BY_Gpa = Comparator.comparingInt(Student::getGpa);