一文搞定Comparable和Comparator
日常求贊,感謝老闆。
歡迎關注公衆號:其實是白羊。乾貨持續更新中…
一、Comparable
(1)、定義
首先Comparable是Java提供的一個接口、裏面只有一個方法:
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*/
public int compareTo(T o);
翻一下上面的註解:
比較此對象和指定對象的順序
- 當此對象小於指定對象時返回負數
- 當此對象等於指定對象時返回0
- 當此對象大於指定對象時返回正數
由此可見這個接口提供的方法可以用來比較實現了此接口的對象的順序(“大小”),常見的如:String、Integer等類都實現了這個接口,所以這些對象都可以使用compareTo方法來進行比較。
(2)、舉個栗子
Integer
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
可見當此對象值<比較對象的值是返回-1,相等返回0,大於返回1(和接口定義的方法含義一致)
(3)、場景
- 當存儲到Collection、Array中時,可以直接使用Collections和Arrays的sort方法進行排序,排序規則爲元素對象重寫的compareTo方法。
- 當這些類存儲到如TreeSet或TreeMap中時,會自動根據重寫的compareTo方法來進行排序存儲。
- 實現了這個接口的類之間調用compareTo進行比較。
二、Comparator
(1)、定義
字面意思理解下,比較器,用來指定比較規則。
接口Comparator,實現該接口並在實現時指定類型,重寫compare方法,就可以規定指定類型的比較規則。
(2)、舉個栗子
我現在創建了一個bean叫TestBean:
@Data
public class TestBean {
private int id;
private String name;
}
我將要把他存放到集合中,且要根據TestBean裏的id屬性的值進行倒敘排序。這樣就可以寫個類實現Comparator接口且泛型爲TestBean。
@Override
public int compare(TestBean o1, TestBean o2) {
int id1 = o1.getId();
int id2 = o2.getId();
if (id1 < id2) {
return 1;
}
if (id1 > id2) {
return -1;
}
return 0;
}
講下爲啥這樣寫:
首先要知道正序情況下:<返回-1,=返回0,>返回1,這個和compareTo的比較是一樣的,所以說倒序的話就是反過來:<返回1,=返回0,>返回-1
精簡寫法:
@Override
public int compare(TestBean o1, TestBean o2) {
int id1 = o1.getId();
int id2 = o2.getId();
return id2 - id1;
}
id2-id1:如果id1<id2那id2-id1即爲正數,如果id1>id2那id2-id1即爲負數,剛好符合邏輯。
(3)、場景
上面例子裏已經是一個場景了(集合中進行元素的自定義排序)
- Collections.sort()/Arrays.sort(),如果沒實現Comparable,是不能直接進行排序的,這就可以在第二個參數加入實現了Comparator接口的比較器,完成自己的比較規則。
- List對象的sort方法,必須傳入比較器
三、最後
總結內容
更多資源:其實是白羊
歡迎star
日常求贊
- 如果你認爲本文對你有幫助,還請「在看/轉發/贊/star」,多謝
- 如果你還發現了更好或不同的想法,還請在留言區不吝賜教,一起探討交流修改,萬分感謝
歡迎關注公衆號:「其實是白羊」乾貨持續更新中…
- 如果你認爲本文對你有幫助,還請「在看/轉發/贊/star」,多謝
- 如果你還發現了更好或不同的想法,還請在留言區不吝賜教,一起探討交流修改,萬分感謝
歡迎關注公衆號:「其實是白羊」乾貨持續更新中…