核心定位對比
| 維度 | java.util.Collection | java.util.Collections |
| 類型 | 介面 (頂層集合接口) | 最終類 (工具類/幫助類) |
| 實例化 | 不可直接實例化,有具體子類 | 不能實例化 (私有構造器),全靜態方法 |
| 核心功能 | 定義集合通用契約 (增刪改查、迭代、大小) | 提供集合操作算法 (排序、查找、同步包裝、不可變視圖) |
| 繼承體系 | → List, Set, Queue, Deque | 無繼承,獨立工具類 |
Collection 接口層級結構
Collection (interface)
├── List (有序、可重複)
│ ├── ArrayList
│ ├── LinkedList
│ ├── Vector (同步,舊)
│ └── Stack (Vector 子類)
├── Set (無序、唯一)
│ ├── HashSet (HashMap 底層)
│ ├── LinkedHashSet (保持插入序)
│ └── TreeSet (紅黑樹,有序)
└── Queue (隊列)
├── PriorityQueue (堆)
├── ArrayDeque (雙端隊列,推薦替代 Stack)
└── BlockingQueue (介面) → ArrayBlockingQueue, LinkedBlockingQueue...
Collections 工具類核心靜態方法
| 分類 | 方法示例 | 說明 |
| 排序 | sort(List<T>) | 自然順序 (元素需實現 Comparable) |
sort(List<T>, Comparator) | 自定義比較器 |
reverse(List) | 反轉順序 |
shuffle(List) | 隨機打亂 |
| 查找/極值 | binarySearch(List, key) | 二分查找 (列表必須有序) |
max(Collection) / min(Collection) | 最大/最小元素 |
frequency(Collection, o) | 元素出現次數 |
| 同步包裝 | synchronizedList(List) | 返回線程安全 List (粗粒度鎖) |
synchronizedSet(Set) | 線程安全 Set |
synchronizedMap(Map) | 線程安全 Map |
synchronizedCollection(Collection) | 通用包裝 |
不可變視圖 (Java 10+ 推薦 List.of 等) | unmodifiableList(List) | 只讀視圖,底層修改可見,嘗試修改拋 UOE |
unmodifiableSet/Map/Collection | 同上 |
emptyList/Set/Map() | 共享空不可變實例 |
| 其他 | swap(List, i, j), rotate(List, distance), disjoint(Collection, Collection) | 交換、旋轉、判斷無交集 |
實戰代碼示例
import java.util.*;
public class Demo {
public static void main(String[] args) {
List scores = new ArrayList<>(Arrays.asList(112.0, 111.0, 23.0, 456.0, 231.0));
// 1. 排序 (自然順序)
Collections.sort(scores);
System.out.println("排序後: " + scores); // [23.0, 111.0, 112.0, 231.0, 456.0]
// 2. 二分查找 (前提有序)
int idx = Collections.binarySearch(scores, 112.0);
System.out.println("112 索引: " + idx); // 2
// 3. 最大/最小
System.out.println("最高分: " + Collections.max(scores)); // 456.0
// 4. 線程安全包裝 (僅簡單場景,高併發用 ConcurrentHashMap)
List safeList = Collections.synchronizedList(new ArrayList<>());
// 遍歷時必須手動同步
synchronized (safeList) {
for (String s : safeList) { /* ... */ }
}
// 5. 不可變視圖
List unmod = Collections.unmodifiableList(List.of("A", "B"));
// unmod.add("C"); // 拋 UnsupportedOperationException
}
}
現代替代方案 (Java 8+)
- 創建不可變集合:
List.of(), Set.of(), Map.of() (Java 9+),List.copyOf() (Java 10+)。
- 排序:
list.sort(Comparator) (默認方法),stream().sorted()。
- 並發安全:
ConcurrentHashMap, CopyOnWriteArrayList,避免 Collections.synchronizedXxx 粗粒度鎖。
- 工具方法遷移:
Collections.max → stream().max(),frequency → stream().filter(...).count()。