2023-09-27|閱讀時間 ‧ 約 8 分鐘

Comparator vs Comparable

使用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裡面已經先定義好該如何比較了


分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.