Comparator vs Comparable

閱讀時間約 8 分鐘

使用Comparator

class Student{
int id;
String name;

public Student(int id, String name) {
this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

public class Demo {
public static void main(String[] args) {

List<Student> studentList = new ArrayList<>();

studentList.add(new Student(2, "Chris"));
studentList.add(new Student(1, "Genos"));
studentList.add(new Student(4, "Mike"));
studentList.add(new Student(3, "Jack"));

System.out.println(studentList);
// [Student{id=2, name='Chris'}, Student{id=1, name='Genos'}, Student{id=4, name='Mike'}, Student{id=3, name='Jack'}]

Comparator<Student> comparator = new Comparator<>(){

@Override
public int compare(Student s1, Student s2) {
if(s1.id > s2.id) return 1;
else if(s1.id < s2.id) return -1;
return 0;
}
};

Collections.sort(studentList, comparator);

System.out.println(studentList);
// [Student{id=1, name='Genos'}, Student{id=2, name='Chris'}, Student{id=3, name='Jack'}, Student{id=4, name='Mike'}]
}
}

排序前,將list印出來看的話,會按照我們所add進list的順序而顯示 (第29行)

按照自行定義的Comparator進行排序 (第32~42行)

排序之後,印出來的結果將會按照我們定義的Comparator的compare方法而排序,我要求以id由小到大排序


使用Comparable

class Student implements Comparable<Student> {
int id;
String name;

public Student(int id, String name) {
this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}

@Override
public int compareTo(Student otherStudent) {
if(this.id > otherStudent.id) return 1;
else if(this.id < otherStudent.id) return -1;
return 0;
}
}

public class Demo {
public static void main(String[] args) {

List<Student> studentList = new ArrayList<>();

studentList.add(new Student(2, "Chris"));
studentList.add(new Student(1, "Genos"));
studentList.add(new Student(4, "Mike"));
studentList.add(new Student(3, "Jack"));

System.out.println(studentList);
// [Student{id=2, name='Chris'}, Student{id=1, name='Genos'}, Student{id=4, name='Mike'}, Student{id=3, name='Jack'}]

Collections.sort(studentList);

System.out.println(studentList);
// [Student{id=1, name='Genos'}, Student{id=2, name='Chris'}, Student{id=3, name='Jack'}, Student{id=4, name='Mike'}]
}
}

與上一個方法的差別在於

Student class implements了Comparable,並且重寫了compareTo方法

注意implements Comparable<Student> 有指定Student型態

compareTo方法的內容和前一個方法的compare方法一樣

只是compareTo方法的參數只會傳入一個,也就是Student型態的物件

也就是要被比較的Student物件


因此第39行的Collections.sort(studentList); 部分,就不需要特地指定要使用哪一個Comparator作排序規則參考

因為我們的Student class裡面已經先定義好該如何比較了


6會員
18Content count
我的Java學習日記
留言0
查看全部
發表第一個留言支持創作者!
併發,多個事情在同一時間段內同時發生 並行,多個事情在同一個時間點上同時發生
Map是由Key-Value所組成的 而Key的部分不能重複,因為是Set
Set 是繼承 Collection API的一個子接口 interface 唯一的限制是不允許重覆的物件存在 所以當不想有相同的物件出現,就可以選擇用Set
程式建立thread,然後會交給硬體中的scheduler去排定執行、切換資源 我們無法強制指定順序,因為電腦有太多任務需要執行,但資源有限,因此會由scheduler去分配、切換資源 電腦能同時執行多項任務
Error分為三種 Compile time error Runtime error 俗稱(Exception) Logical error
普通的interface:有一個以上的abstract method Functinal Interface...
併發,多個事情在同一時間段內同時發生 並行,多個事情在同一個時間點上同時發生
Map是由Key-Value所組成的 而Key的部分不能重複,因為是Set
Set 是繼承 Collection API的一個子接口 interface 唯一的限制是不允許重覆的物件存在 所以當不想有相同的物件出現,就可以選擇用Set
程式建立thread,然後會交給硬體中的scheduler去排定執行、切換資源 我們無法強制指定順序,因為電腦有太多任務需要執行,但資源有限,因此會由scheduler去分配、切換資源 電腦能同時執行多項任務
Error分為三種 Compile time error Runtime error 俗稱(Exception) Logical error
普通的interface:有一個以上的abstract method Functinal Interface...
你可能也想看
Google News 追蹤
Thumbnail
本專欄將提供給您最新的市場資訊、產業研究、交易心法、優質公司介紹,以上內容並非個股分析,還請各位依據自身狀況作出交易決策。歡迎訂閱支持我,獲得相關內容,也祝您的投資之路順遂! 每年 $990 訂閱方案👉 https://reurl.cc/VNYVxZ 每月 $99 訂閱方案👉https://re
Thumbnail
某天在檢視~/AppData/Roaming裡面的資料,看看有沒有垃圾要手動清理,一個不小心砍掉了VSCode的設定資料夾,以至於重新開啟後整個頁面跟剛下載來安裝後的編輯器沒兩樣,乾脆趁這機會整理一下日常配置設定,哪天換新機或是又手殘了也能快速復原歸位。
首先要安裝vscode : Visual Studio Code - Code Editing. Redefined 安裝後我們就可以把她打開來,接著去檔案 -> 喜好設定 -> 設定檔(預設) -> 你就會看到設定裡面的 settings.json,就可以開始你的設定拉(主要是依照個人的喜好設定
Introduction: The integration of digital ticketing platforms in the retail sector has redefined how businesses engage with customers, manage events, a
Thumbnail
教大家讓 vscode 連上遠端電腦中的 docker 環境之中,步驟詳細且附圖
兩種方式進行物件比較,使用Comparator或使用Comparable
👨‍💻Intro 為了實現vscode在wsl環境下使用ssh連接到gce的需求,在爬文後找到一篇解法,因此記錄下來,方便日後查詢 🎯setup 建立ssh.bat檔案,並放在windows下任意位置 2. vscode設定ssh.bat路徑 打開vscode的settings -> exte
Thumbnail
探索如何在 VS Code 中養一隻療癒的小寵物。本文將指導你安裝和使用 vscode-pets 擴充功能,讓可愛的寵物陪伴你一同寫程式。你可以選擇不同類型和顏色的寵物,甚至改變它們的遊玩場景,為你的編程時光增添樂趣和舒適。
Thumbnail
這次要介紹的兩個叫做 VSTACK 跟 HSTACK,可以讓你把範圍縱向或橫向堆疊起來,省去合併資料的一點麻煩!
Thumbnail
第一:vs和v.s. 第二:ex.和e.g. 第三:et al.和ibid. 第四:NG和MV
Thumbnail
本篇目標:ftp-simple 連接與使用 本篇適合:需要使用Visual Studio Code 連接伺服器進行程式寫作的朋友 過去因為在實驗室的經驗,所有的程式皆存放在實驗室的伺服器上,因此我們會需要用本機的電腦嘗試連接到伺服器進行寫作。
Thumbnail
本專欄將提供給您最新的市場資訊、產業研究、交易心法、優質公司介紹,以上內容並非個股分析,還請各位依據自身狀況作出交易決策。歡迎訂閱支持我,獲得相關內容,也祝您的投資之路順遂! 每年 $990 訂閱方案👉 https://reurl.cc/VNYVxZ 每月 $99 訂閱方案👉https://re
Thumbnail
某天在檢視~/AppData/Roaming裡面的資料,看看有沒有垃圾要手動清理,一個不小心砍掉了VSCode的設定資料夾,以至於重新開啟後整個頁面跟剛下載來安裝後的編輯器沒兩樣,乾脆趁這機會整理一下日常配置設定,哪天換新機或是又手殘了也能快速復原歸位。
首先要安裝vscode : Visual Studio Code - Code Editing. Redefined 安裝後我們就可以把她打開來,接著去檔案 -> 喜好設定 -> 設定檔(預設) -> 你就會看到設定裡面的 settings.json,就可以開始你的設定拉(主要是依照個人的喜好設定
Introduction: The integration of digital ticketing platforms in the retail sector has redefined how businesses engage with customers, manage events, a
Thumbnail
教大家讓 vscode 連上遠端電腦中的 docker 環境之中,步驟詳細且附圖
兩種方式進行物件比較,使用Comparator或使用Comparable
👨‍💻Intro 為了實現vscode在wsl環境下使用ssh連接到gce的需求,在爬文後找到一篇解法,因此記錄下來,方便日後查詢 🎯setup 建立ssh.bat檔案,並放在windows下任意位置 2. vscode設定ssh.bat路徑 打開vscode的settings -> exte
Thumbnail
探索如何在 VS Code 中養一隻療癒的小寵物。本文將指導你安裝和使用 vscode-pets 擴充功能,讓可愛的寵物陪伴你一同寫程式。你可以選擇不同類型和顏色的寵物,甚至改變它們的遊玩場景,為你的編程時光增添樂趣和舒適。
Thumbnail
這次要介紹的兩個叫做 VSTACK 跟 HSTACK,可以讓你把範圍縱向或橫向堆疊起來,省去合併資料的一點麻煩!
Thumbnail
第一:vs和v.s. 第二:ex.和e.g. 第三:et al.和ibid. 第四:NG和MV
Thumbnail
本篇目標:ftp-simple 連接與使用 本篇適合:需要使用Visual Studio Code 連接伺服器進行程式寫作的朋友 過去因為在實驗室的經驗,所有的程式皆存放在實驗室的伺服器上,因此我們會需要用本機的電腦嘗試連接到伺服器進行寫作。