相同
- Comparable和Comparator都是用來實作對象的比較、排序
- 要想對象比較、排序,都需要實作Comparable或Comparator接口
- Comparable和Comparator都是Java的接口
差別
- Comparator位于java.util包下,而Comparable位于java.lang包下
- Comparable接口的實作是在類的内部(如 String、Integer已經實作了Comparable接口,自己就可以完成比較大小操作),Comparator接口的實作是在類的外部(可以了解為一個是自已完成比較,一個是外部程式實作比較)
- 實作Comparable接口要覆寫compareTo方法, 在compareTo方法裡面實作比較
public class Student implements Comparable { String name; int age public int compareTo(Student another) { int i = 0; i = name.compareTo(another.name); if(i == 0) { return age - another.age; } else { return i; } } } 這時我們可以直接用 Collections.sort( StudentList ) 對其排序了.( **隻需傳入要排序的清單**)
- 實作Comparator需要覆寫 compare 方法
public class Student{ String name; int age }class StudentComparator implements Comparator { public int compare(Student one, Student another) { int i = 0; i = one.name.compareTo(another.name); if(i == 0) { return one.age - another.age; } else { return i; } } } Collections.sort( StudentList , new StudentComparator()) 可以對其排序( **不僅要傳入待排序的清單,還要傳入實作了Comparator的類的對象**)