平常求贊,感謝老闆。歡迎關注公衆號:實際上是白羊。乾貨持續更新中......java
首先Comparable是Java提供的一個接口、裏面只有一個方法:git
/** * 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);
翻一下上面的註解:less
比較此對象和指定對象的順序ide
因而可知這個接口提供的方法能夠用來比較實現了此接口的對象的順序(「大小」),常見的如:String、Integer等類都實現了這個接口,因此這些對象均可以使用compareTo方法來進行比較。this
Integerspa
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(和接口定義的方法含義一致)code
字面意思理解下,比較器,用來指定比較規則。對象
接口Comparator<T>,實現該接口並在實現時指定類型,重寫compare方法,就能夠規定指定類型的比較規則。排序
我如今建立了一個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即爲負數,恰好符合邏輯。
上面例子裏已是一個場景了(集合中進行元素的自定義排序)
總結內容
更多資源: 實際上是白羊歡迎star
平常求贊
- 若是你認爲本文對你有幫助,還請「在看/轉發/贊/star」,多謝
- 若是你還發現了更好或不一樣的想法,還請在留言區不吝賜教,一塊兒探討交流修改,萬分感謝
歡迎關注公衆號:「實際上是白羊」乾貨持續更新中......