List、Set、Queue 父接口)java.util.Collections 工具類,全 static 方法,操作/返回集合| 類別 | 方法 | 說明 |
|---|---|---|
| 排序 | sort(List) | 自然序排序 (元素需 Comparable) |
sort(List, Comparator) | 指定比較器排序 | |
reverse(List) | 反轉順序 | |
shuffle(List) | 隨機打亂 (洗牌算法) | |
| 查找/替換 | binarySearch(List, key) | 二分查找 (列表必須有序) |
binarySearch(List, key, Comparator) | 指定比較器二分查找 | |
max(Collection) / min(Collection) | 最大/最小元素 (自然序) | |
max(Collection, Comparator) | 指定比較器最大/最小 | |
replaceAll(List, oldVal, newVal) | 替換所有匹配元素 | |
| 同步包裝 | synchronizedCollection(Collection) | 線程安全包裝 (裝飾器模式) |
synchronizedList/List/Set/Map | 各類型專用包裝 | |
unmodifiableCollection/List/Set/Map | 不可變視圖 (只讀) | |
checkedCollection/List/Set/Map | 類型安全檢查視圖 (運行時檢查) | |
| 特殊集合 | emptyList/Set/Map() | 不可變空集合 (單例) |
singleton(obj) / singletonList/Map | 單元素不可變集合 | |
nCopies(n, obj) | N 個引用同一對象的列表 | |
frequency(Collection, obj) | 統計元素出現次數 | |
| 工廠/轉換 | enumeration(Collection) | 轉 Enumeration (舊 API 兼容) |
list(Enumeration) | Enumeration 轉 ArrayList | |
addAll(Collection, elements...) | 批量添加 (可變參數) |
// 核心思想:裝飾器模式,所有方法 synchronized 加鎖
static class SynchronizedList extends SynchronizedCollection implements List {
final List list;
final Object mutex; // 鎖對象,默認 this,可傳入外部鎖
public E get(int index) {
synchronized (mutex) { return list.get(index); }
}
// ... 所有方法同步
// 迭代器需手動同步!
public Iterator iterator() {
return list.iterator(); // 返回原始迭代器,用戶必須手動 synchronized(mutex)
}
}
關鍵警示:synchronizedList 迭代時必須手動同步鎖對象,否則非線程安全:
List syncList = Collections.synchronizedList(new ArrayList<>());
// 錯誤:併發修改異常
for (String s : syncList) { ... }
// 正確:手動同步
synchronized (syncList) {
for (String s : syncList) { ... }
}
// 或用 CopyOnWriteArrayList (無需同步遍歷)
static class UnmodifiableList extends UnmodifiableCollection implements List {
final List list;
public E get(int index) { return list.get(index); }
public E set(int index, E element) { throw new UnsupportedOperationException(); }
public void add(int index, E element) { throw new UnsupportedOperationException(); }
// ... 所有修改方法拋異常
}
注意:僅是視圖,底層集合修改仍會反映到視圖。真正不可變請用 List.of() (JDK 9+) 或 ImmutableList (Guava)。
List safe = Collections.checkedList(new ArrayList<>(), String.class);
safe.add("OK");
safe.add(123); // 運行時拋 ClassCastException (而非編譯錯誤),用於調試泛型擦除問題
List users = ...;
// 多字段排序:先按年齡升序,再按姓名降序
users.sort(Comparator.comparing(User::getAge)
.thenComparing(User::getName, Comparator.reverseOrder()));
// 或 Collections.sort
Collections.sort(users, (u1, u2) -> {
int c = Integer.compare(u1.getAge(), u2.getAge());
if (c != 0) return c;
return u2.getName().compareTo(u1.getName()); // 姓名降序
});
List sorted = Arrays.asList(1, 3, 5, 7, 9);
int idx = Collections.binarySearch(sorted, 5); // 返回 2
int notFound = Collections.binarySearch(sorted, 4); // 返回 -3 (-(插入點+1))
// 插入點 = -(-3) - 1 = 2,即應插入索引 2 保持有序
List deck = new ArrayList<>(52);
// 初始化...
Collections.shuffle(deck); // Fisher-Yates 洗牌,O(n),均勻隨機
// 指定 Random 種子可復現
Collections.shuffle(deck, new Random(42));
// 避免創建多個空列表對象
public List getEmpty() {
return Collections.emptyList(); // 返回同一單例 EMPTY_LIST
}
// 方法參數防空
public void process(List items) {
List list = items != null ? items : Collections.emptyList();
// 安全遍歷
}
Set singleton = Collections.singleton("ONLY_ONE"); // 不可變、高效
Map singletonMap = Collections.singletonMap("key", "value");
| Collections 方法 | 現代替代 | 優勢 |
|---|---|---|
unmodifiableList | List.of() / List.copyOf() | 真正不可變、內存緊湊、編譯期類型安全 |
singletonList | List.of(element) | 同上 |
emptyList | List.of() | 同上 |
synchronizedList | CopyOnWriteArrayList / 並發集合 | 無鎖遍歷、更高並發性能 |
checkedList | 編譯期泛型 + 單元測試 | 靜態檢查優於運行時 |
sort | list.sort(comparator) | 實例方法、鏈式調用 |
binarySearch | Collections.binarySearch 仍通用 | 無直接替代 |
shuffle | Collections.shuffle 仍通用 | 無直接替代 |
frequency | Collections.frequency / Stream filter().count() | Stream 更靈活 |
| 包裝類型 | 讀性能 | 寫性能 | 遍歷安全 | 適用場景 |
|---|---|---|---|---|
| Collections.synchronizedXxx | 鎖開銷 | 鎖開銷 | 需手動同步 | 低併發、舊代碼兼容 |
| CopyOnWriteArrayList | 極快 (無鎖) | 慢 (複製數組) | ✅ 安全 | 讀多寫極少、遍歷頻繁 |
| ConcurrentHashMap | 極快 (分段/CAS) | 快 (細粒度鎖) | ✅ 弱一致性 | 高併發 Map |
| List.of / Set.of | 極快 (不可變) | 不支持 | ✅ 天然安全 | 只讀數據、常量、配置 |
synchronized(list) 遍歷Collections.nCopies(3, new ArrayList()) 三個引用指向同一列表CopyOnWriteArrayList、ConcurrentHashMap 替代同步包裝Collections 是 Java 集合框架的「瑞士軍刀」,提供排序、查找、同步包裝、不可變視圖、特殊單例、工廠轉換等靜態工具方法。核心實現基於裝飾器模式,同步包裝器需注意迭代器手動同步,不可變視圖僅屏蔽修改方法。現代開發優先使用 JDK 9+ List.of()、並發集合、實例方法 list.sort(),Collections 仍作為補充工具 (shuffle、binarySearch、frequency 等) 發揮價值。掌握其 API 分類、實現原理、線程安全邊界與現代替代,能寫出更簡潔、高效、安全的集合操作代碼。