java.util.Collections 是操作 Collection、Map 的「瑞士軍刀」,提供 30+ 個 static 方法,覆蓋排序、二分查找、反轉、洗牌、交換、填充、同步包裝、不可視圖等高頻場景。本文精選 6 大核心方法實戰演示,助你少寫樣板代碼。
| 方法 | 簽名 | 作用 | 前置條件 |
|---|---|---|---|
| sort | sort(List<T> list) / sort(List<T>, Comparator) | 自然順序/定制順序排序 | 元素實現 Comparable / 傳 Comparator |
| binarySearch | binarySearch(List<T>, T key) / binarySearch(List<T>, T, Comparator) | 二分查找索引 | 列表必須已排序 |
| reverse | reverse(List<?> list) | 原地反轉列表 | 無 |
| shuffle | shuffle(List<?> list) / shuffle(List<?>, Random) | 隨機打亂 (洗牌算法) | 無 |
| swap | swap(List<?>, int i, int j) | 交換兩個位置元素 | 索引合法 |
| fill | fill(List<? super T>, T obj) | 用指定元素替換所有位置 | 無 |
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList(
"zhangsan", "lisi", "wangwu", "zhaoliu", "tianqi"
));
print("初始", list);
// 1. 交換索引 1 和 2
Collections.swap(list, 1, 2);
print("swap(1,2)", list); // lisi <-> wangwu
// 2. 自然排序 (字典序)
Collections.sort(list);
print("sort()", list); // lisi, tianqi, wangwu, zhangsan, zhaoliu
// 3. 二分查找 (前提:已排序)
int idx = Collections.binarySearch(list, "zhaoliu");
System.out.println("binarySearch('zhaoliu') = " + idx); // 4
// 4. 打亂順序
Collections.shuffle(list);
print("shuffle()", list); // 隨機順序
// 5. 填充統一值
Collections.fill(list, "jay");
print("fill('jay')", list); // [jay, jay, jay, jay, jay]
}
static void print(String label, List list) {
System.out.print(label + ": ");
list.forEach(s -> System.out.print(s + " "));
System.out.println();
}
}
未排序列表調用結果不可預測 (可能返回負數插入點)。永遠在 sort 後調用。
Arrays.sort (雙軸快排,不穩定);對象列表用 Collections.sort (穩定)。// 可復現的洗牌 (測試/調試用)
Collections.shuffle(list, new Random(12345L));
// 線程安全 List/Set/Map (性能一般,高併發建議用 java.util.concurrent)
List syncList = Collections.synchronizedList(new ArrayList<>());
Set syncSet = Collections.synchronizedSet(new HashSet<>());
Map syncMap = Collections.synchronizedMap(new HashMap<>());
// 迭代時必須手動同步鎖住集合對象!
synchronized (syncList) {
for (String s : syncList) { /* ... */ }
}
// 不可修改視圖 (防禦性編程)
List unmod = Collections.unmodifiableList(list);
unmod.add("x"); // 拋 UnsupportedOperationException
Collections.max(list); // 自然順序最大值
Collections.min(list, cmp); // 定制比較器最小值
Collections.frequency(list, "a"); // 統計元素出現次數
Collections.disjoint(list1, list2); // 判斷無交集
Collections 以靜態方法封裝經典算法,排序用 sort、查找用 binarySearch (前提有序)、打亂用 shuffle、填充用 fill、交換用 swap、反轉用 reverse。掌握這 6 大核心 + 同步包裝/不可視圖/極值統計,日常集合操作無需造輪子。記住:binarySearch 前必排序,shuffle 可指定種子,同步包裝迭代必加鎖。