java.util.Collections 是集合框架的核心工具類,提供排序、搜尋、線程安全包裝等靜態方法,是操作集合對象的利器。
Collections.sort() 支援兩類列表排序:
Comparable 介面(如 Integer、String、自訂類別)Comparator 實例,適用無法修改類別或需多種排序規則的場景| 特性 | Comparable | Comparator |
|---|---|---|
| 定位 | 內部比較器,定義預設自然順序 | 外部比較器,定義臨時/多種規則 |
| 方法 | compareTo(T o) | compare(T o1, T o2) |
| 回傳值 | 正數:大於、負數:小於、0:相等 | 同左 |
| 適用場景 | 類別擁有單一明確排序邏輯 | 需多種排序、無法修改源碼、第三方類別 |
public class Student implements Comparable<Student> {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
// getter/setter 省略...
@Override
public int compareTo(Student o) {
return this.id.compareTo(o.id); // 按 ID 自然排序
}
}
public class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName()); // 按姓名排序
}
}
public class CollectionTest {
// 1. Integer 列表自然排序
public void testSort1() {
List<Integer> list = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 10; i++) {
Integer k;
do { k = rand.nextInt(100); } while (list.contains(k));
list.add(k);
System.out.println("新增:" + k);
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序後:" + list);
}
// 2. String 列表自然排序
public void testSort2() {
List<String> list = Arrays.asList("del", "lenovo", "ios", "apple");
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序後:" + list);
}
// 3. 自訂物件:自然排序 + 定制排序
public void testSort3() {
List<Student> students = new ArrayList<>();
Random rand = new Random();
students.add(new Student(rand.nextInt(1000)+"", "小明"));
students.add(new Student(rand.nextInt(1000)+"", "小紅"));
students.add(new Student(rand.nextInt(1000)+"", "小兵"));
students.add(new Student(rand.nextInt(1000)+"", "abcde"));
System.out.println("原始順序:");
students.forEach(s -> System.out.println(s.getId() + " " + s.getName()));
Collections.sort(students); // 自然排序(按 ID)
System.out.println("按 ID 排序後:");
students.forEach(s -> System.out.println(s.getId() + " " + s.getName()));
Collections.sort(students, new StudentComparator()); // 定制排序(按姓名)
System.out.println("按姓名排序後:");
students.forEach(s -> System.out.println(s.getId() + " " + s.getName()));
}
public static void main(String[] args) {
new CollectionTest().testSort3();
}
}
Comparable 定義「是什麼順序」,Comparator 定義「怎麼比較」Comparable,修改類別源碼