Comparable 在编写类的时候实现这个结构,并重写compareTo方法
Comparator 在使用Collections.sort(List list,Comparetor c)方法时,建立Comparetor对象,并重写compare方法
java.lang.Comparable 接口 :强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo方法被称为它的自然比较方法。只能在类中实现compareTo()一次,不能经常修改类的代码。实现自己想要的排序。实现此接口的对象列表(和数组)可以通过Collections.sort(和Arrays.sort)进 行自动排序,对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。
当创建的对象需要实现比较大小功能的时候,必须实现此接口,否则报类型转换异常。比如TreeSet集合是有序集合,系统默认按自然顺序排序。
使用:先用类实现Comparable接口,然后在类中重写compareTo方法,
public int compareTo(Object o){
写比较逻辑
return 0;(0表示一样大,正表示 this大,负表示 o 大)
}
set集合里,如果return 0,则认为是重复元素,不会存入
public class Student implements Comparable{
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
//重写compareTo方法
@Override
public int compareTo(Object o) {
Student s=(Student) o;
return (int)(s.score-this.score);
}
java.util.Comparator 接口 :
强行对某个对象进行整体排序。
可以将
Comparator
传递给
sort
方法(如Collections.sort 或
Arrays.sort
),从而允许在排序顺序上实现精确控制。还可以使用
Comparator来控制某些数据结构 (如有序
set
或有序映射)的顺序,或者为那些没有自然顺序的对象
collection
提供排序。
使用:
采用
Collections.sort(List list,Comparetor c)
方
式,自己定义规则
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge()-o1.getAge();//以学生的年龄降序
}
});