Java 提供兩大排序介面:Comparable<T>(內部比較)與 Comparator<T>(外部比較器)。本文通過完整代碼範例解析兩者定義、使用場景、策略模式應用與選型建議。
public interface Comparable<T> {
int compareTo(T o);
}
public class Student implements Comparable<Student> {
private String name;
private int age;
// 構造器、getter/setter 省略
@Override
public int compareTo(Student other) {
if (this.age != other.age) return Integer.compare(this.age, other.age);
return this.name.compareTo(other.name); // 年齡相同按姓名
}
}
// 使用
List<Student> list = Arrays.asList(
new Student("xiaosi", 24),
new Student("sunny", 24),
new Student("yoona", 21),
new Student("kim", 27)
);
Collections.sort(list);
// 輸出:yoona(21) → sunny(24) → xiaosi(24) → kim(27)
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj); // 通常不需覆寫
}
public class Teacher {
private String name;
private int age;
// 省略 getter/setter
}
public class TeacherComparator implements Comparator<Teacher> {
@Override
public int compare(Teacher t1, Teacher t2) {
if (t1.getAge() != t2.getAge()) return Integer.compare(t1.getAge(), t2.getAge());
return t1.getName().compareTo(t2.getName());
}
}
// 使用
Collections.sort(teachers, new TeacherComparator());
| 維度 | Comparable | Comparator |
|---|---|---|
| 實現位置 | 實體類別內部 | 獨立類別(外部) |
| 修改實體類 | 需修改源碼 | 無需修改 |
| 比較策略數 | 單一(自然順序) | 無限多(可插拔) |
| 適用場景 | 領域模型有明確預設排序 | 多維度排序、第三方類、臨時排序 |
| 設計模式 | —— | 策略模式 |
| 泛型靈活性 | 綁定自身類型 | 可比較任意類型 |