public interface Comparable<T> {
public int compareTo(T o);
}
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
作用:用来实现实际中元素的比较和排序
Comparable强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。
Comparator强行对某个对象 collection 进行整体排序 的比较函数。可以将 Comparator 传递给 sort 方法(如 Collections.sort 或 Arrays.sort),从而允许在排序顺序上实现精确控制。还可以使用 Comparator 来控制某些数据结构(如有序 set或有序映射)的顺序,或者为那些没有自然顺序的对象 collection 提供排序。
可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。
模式
用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
Comparator可以看成一种算法的实现,将算法和数据分离。
案例:成绩降序排练,成绩相同,按照年纪从小到大
public class Student {
public static void main(String[] args) {
ArrayList<StudentSort> data = new ArrayList<>();
StudentSort jby = new StudentSort("贾宝玉", 14, 88.5);
StudentSort ldy = new StudentSort("林黛玉", 13, 88.5);
StudentSort sxy = new StudentSort("史湘云", 13, 85);
StudentSort xbc = new StudentSort("薛宝钗", 15, 91);
data.add(jby);
data.add(ldy);
data.add(sxy);
data.add(xbc);
Collections.sort(data);
for (StudentSort sort : data) {
System.out.println(sort);
}
System.out.println("-----------------");
Collections.sort(data, new comparator());
for (StudentSort sort : data) {
System.out.println(sort);
}
}
static class StudentSort implements Comparable<StudentSort> {
private String name;
private int age;
private double fraction;
@Override
public int compareTo(StudentSort o) {
if (this.fraction > o.fraction) {
return -1;
} else if (this.fraction == o.fraction ) {
if (this.age > age) {
return 1;
}
return -1;
/*return this.age-this.age ;*/
}else
return 1;
}
public StudentSort() {
}
public StudentSort(String name, int age, double fraction) {
this.name = name;
this.age = age;
this.fraction = fraction;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getFraction() {
return fraction;
}
public void setFraction(double fraction) {
this.fraction = fraction;
}
@Override
public String toString() {
return "Sort{" +
"name='" + name + '\'' +
", age=" + age +
", fraction=" + fraction +
'}';
}
}
static class comparator implements Comparator<StudentSort> {
@Override
public int compare(StudentSort o1, StudentSort o2) {
if (o1.fraction == o2.fraction) {
return o1.age - o2.age;
}
if (o1.fraction > o2.fraction) {
return -1;
} else if (o1.fraction < o2.fraction) {
return 1;
} else {
return 0;
}
}
}
}