对比
Comparable | Comparator | |
---|---|---|
词性 | 形容词 | 名词 |
释义 | 可比较的 | 比较器 |
类型 | 接口 | 接口 |
抽象方法 | int compareTo(T o) | int compare(T o1, T o2) |
目的 | 自比较 | 它比较 |
实现Comparable接口的类,目的是使该类的对象之间可进行比较。当该比较方式满足不了特定需求时,可以创建一个实现了Comparator接口的比较器。比如,People类中,实现Comparable,compareTo方法是比较对象的年龄,当需求出现变化,对象依照身高来比较时,就需要创建一个比较器PeopleComparator了。
示例
public class People implements Comparable<People> {
String name;//姓名
Integer age;//年龄
Double height;//身高
public People() {
}
public People(String name, Integer age, Double height) {
this.name = name;
this.age = age;
this.height = height;
}
/**
* 年龄比较
*
* @param other
* @return
*/
@Override
public int compareTo(People other) {
return this.age - other.age;
}
}
public class PeopleComparator implements Comparator<People> {
/**
* 身高比较
*
* @param p1
* @param p2
* @return
*/
@Override
public int compare(People p1, People p2) {
return (int) (p1.height - p2.height);
}
}
public static void main (String[]args){
People papa = new People("爸爸", 40, 175.0);
People son = new People("儿子", 20, 183.0);
//年龄比较
int ageCompare = papa.compareTo(son);
if (ageCompare>0){
System.out.println("爸爸年龄比儿子大");
}
// 身高比较
int heightCompare=new PeopleComparator().compare(papa,son);
if (heightCompare<0){
System.out.println("儿子比爸爸长得高");
}
}