一文搞定Comparable和Comparator

一文搞定Comparable和Comparator

平常求贊,感謝老闆。

歡迎關注公衆號:實際上是白羊。乾貨持續更新中......java

1、Comparable

(1)、定義

首先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

  1. 當此對象小於指定對象時返回負數
  2. 當此對象等於指定對象時返回0
  3. 當此對象大於指定對象時返回正數

因而可知這個接口提供的方法能夠用來比較實現了此接口的對象的順序(「大小」),常見的如:String、Integer等類都實現了這個接口,因此這些對象均可以使用compareTo方法來進行比較。this

(2)、舉個栗子

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

(3)、場景

  1. 當存儲到Collection、Array中時,能夠直接使用Collections和Arrays的sort方法進行排序,排序規則爲元素對象重寫的compareTo方法。
  2. 當這些類存儲到如TreeSet或TreeMap中時,會自動根據重寫的compareTo方法來進行排序存儲。
  3. 實現了這個接口的類之間調用compareTo進行比較。

2、Comparator

(1)、定義

字面意思理解下,比較器,用來指定比較規則。對象

接口Comparator<T>,實現該接口並在實現時指定類型,重寫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)、場景

上面例子裏已是一個場景了(集合中進行元素的自定義排序)

  1. Collections.sort()/Arrays.sort(),若是沒實現Comparable,是不能直接進行排序的,這就能夠在第二個參數加入實現了Comparator接口的比較器,完成本身的比較規則。
  2. List對象的sort方法,必須傳入比較器

3、最後

總結內容

更多資源: 實際上是白羊

歡迎star

平常求贊

  • 若是你認爲本文對你有幫助,還請「在看/轉發/贊/star」,多謝
  • 若是你還發現了更好或不一樣的想法,還請在留言區不吝賜教,一塊兒探討交流修改,萬分感謝

歡迎關注公衆號:「實際上是白羊」乾貨持續更新中......

相關文章
相關標籤/搜索