Comparable
Comparable可以認為是一個內部比較器,實現了Comparable介面的類有一個特點,就是這些類是可以和自己比較的,在compareTo方法中指定具體的比較方法。
compareTo方法的返回值是int,有三種情況:
1、比較者大於被比較者(也就是compareTo方法裡面的物件),那麼返回正整數
2、比較者等於被比較者,那麼返回0
3、比較者小於被比較者,那麼返回負整數
舉例:定義Student類,實現Comparable介面,重寫compareTo方法,比較兩者的age。
public class Student implements Comparable<Student>{ private String name;
private String age; public Student() {
} public Student(String name, String age) { this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} @Override
public int compareTo(Student o) {
return this.age.compareTo(o.age);
}
}
public class Test {
public static void main(String[] args) {
Student student1 = new Student("zs","11");
Student student2 = new Student("ls","12");
Student student3 = new Student("ww","10");
System.out.println("age 11 與 age 12 比較====" + student1.compareTo(student2));
System.out.println("age 11 與 age 10 比較====" + student1.compareTo(student3));
System.out.println("age 11 與 age 11 比較====" + student1.compareTo(student1));
}
}
結果:
age 11 與 age 12 比較====-1
age 11 與 age 10 比較====1
age 11 與 age 11 比較====0
Comparator
Comparator可以認為是是一個外部比較器,個人認為有兩種情況可以使用實現Comparator介面的方式:
1、一個物件不支援自己和自己比較(沒有實現Comparable介面),但是又想對兩個物件進行比較
2、一個物件實現了Comparable介面,但是開發者認為compareTo方法中的比較方式並不是自己想要的那種比較方式
Comparator接口裡面有一個compare方法,方法有兩個引數T o1和T o2,是泛型的表示方式,分別表示待比較的兩個物件,方法返回值和Comparable介面一樣是int,有三種情況:
1、o1大於o2,返回正整數
2、o1等於o2,返回0
3、o1小於o3,返回負整數
舉例:自定義一個外部比較器StudentComparator,實現Comparator介面,重寫compare方法,比較兩者的age。
public class StudentComparator implements Comparator<Student>{ @Override
public int compare(Student o1, Student o2) {
return o1.getAge().compareTo(o2.getAge());
}
}
public class Test {
public static void main(String[] args) {
Student student1 = new Student("zs","11");
Student student2 = new Student("ls","12");
Student student3 = new Student("ww","10");
StudentComparator studentComparator = new StudentComparator();
int compare1 = studentComparator.compare(student1, student2);
int compare2 = studentComparator.compare(student1, student3);
int compare3 = studentComparator.compare(student1, student1);
System.out.println("age 11 與 age 12 比較======" + compare1);
System.out.println("age 11 與 age 10 比較======" + compare2);
System.out.println("age 11 與 age 11 比較======" + compare3);
}
}
結果:
age 11 與 age 12 比較======-1
age 11 與 age 10 比較======1
age 11 與 age 11 比較======0
總結
總結一下,兩種比較器Comparable和Comparator,後者相比前者有如下優點:
1、如果實現類沒有實現Comparable介面,又想對兩個類進行比較(或者實現類實現了Comparable介面,但是對compareTo方法內的比較演算法不滿意),那麼可以實現Comparator介面,自定義一個比較器,寫比較演算法
2、實現Comparable介面的方式比實現Comparator介面的耦合性要強一些,如果要修改比較演算法,要修改Comparable介面的實現類,而實現Comparator的類是在外部進行比較的,不需要對實現類有任何修改。從這個角度說,其實有些不太好,尤其在我們將實現類的.class檔案打成一個.jar檔案提供給開發者使用的時候。實際上實現Comparator介面的方式後面會寫到就是一種典型的策略模式。
當然,這不是鼓勵用Comparator,意思是開發者還是要在具體場景下選擇最合適的那種比較器而已。
參考資料:
https://www.cnblogs.com/xrq730/p/4850140.html