完全毀滅 Comparable 和 Comparator 帶給個人噩夢

開篇

Comparable 和 Comparator 這兩個接口一直像 「魔鬼」 同樣糾纏着我(在看一些源代碼的時候), 礙於浪費時間就一直懶得研究他們, 由於畢竟迄今爲止我尚未直接使用他們過。今天趁着有空, 來搞一搞這兩個 「B崽子」。ide

從類名上理解

Comparable 是以 able 結尾, 一般表示一個對象具備某種能力, Comparator 是以 or 結尾, 一般表示一個對象是什麼。固然, 這還不足以幫助咱們理解他們的區別, 結合下面幾個方面會好不少。測試

從方法上理解

  • 若是該對象小於、等於或大於指定對象,則分別返回負整數、零或正整數。

先看 Comparable 的, 以下所示。 只有一個入參, 表示被比較的對象。.net

int compareTo(T o);

再看 Comparator 的, 以下所示。 有兩個入參, 他們是相互比較的對象。code

int compare(T o1, T o2);

從使用上理解

從下面的測試過程也能夠輕鬆看出來一些區別對象

public void test(){
	Student s1 = new Student();
	Student s2 = new Student();
	// 使用 Comparable 比較兩個 Student 對象
	int result = s1.compareTo(s2);
	// 使用 Comparator 比較兩個 Student 對象
	int result2 = new StudentComParator().compare(s1, s2);
 }


 class Student implements Comparable<Student> {

	[@Override](https://my.oschina.net/u/1162528)
	public int compareTo(Student s) {
		// 省略比較邏輯
		return 0;
	}
	
 }

 class StudentComParator implements Comparator<Student>{

	[@Override](https://my.oschina.net/u/1162528)
	public int compare(Student o1, Student o2) {
		// 省略比較邏輯
		return 0;
	}
	
 }

總結

兩種方法各有優劣, 用Comparable 簡單, 只要實現Comparable 接口的對象直接就成爲一個能夠比較的對象,可是須要修改源代碼。 用Comparator 的好處是不須要修改源代碼, 而是另外實現一個比較器, 當某個自定義的對象須要做比較的時候,把比較器和對象一塊兒傳遞過去就能夠比大小了, 而且在Comparator 裏面用戶能夠本身實現複雜的能夠通用的邏輯,使其能夠匹配一些比較簡單的對象,那樣就能夠節省不少重複勞動了接口

相關文章
相關標籤/搜索