两者都是作为比较器的接口,底层源码看出Comparator是有@FunctionalInterface注解的,该注解表示这个接口作为一个“函数式接口”,指仅仅只包含一个抽象方法的接口。如果有多个抽象方法时会报错。
使用场景:Comparator在容器中比较对象时适合自定义的对比,比较的灵活。而Comparable比较的是一种固定的,容器里面的对象需要实现Comparable这个接口,在里面重写比较的方法。
Comparator案例:
Collections.max(studentSet, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge() - o2.getAge(); } });
Comparable案例:
@Override public int compareTo(Object o) { if (o instanceof Student) { Student student = (Student) o; return this.age - student.age; }