Java Collections 工具類的第二類方法:返回容器介面對象,完美演示了適配器與裝飾器兩大經典設計模式。本文結合 JDK 源碼,剖析空容器、單例容器、檢查型、同步型、不可修改型包裝器的實現細節與適用邊界。
List<String> list = Collections.emptyList(); // 返回靜態單例 EmptyList
Map<K,V> map = Collections.emptyMap();
Set<E> set = Collections.emptySet();
null,調用者無需判空,統一流程;靜態單例節省內存/創建開銷add/remove 拋 UnsupportedOperationExceptionEmptyList 繼承 AbstractList,size()=0,所有寫操作拋異常Set<String> set = Collections.singleton("hello");
List<String> list = Collections.singletonList("world");
Map<K,V> map = Collections.singletonMap("k", "v");
SingletonSet 只存儲單一元素引用,size()=1,iterator() 返回單元素迭代器list.removeAll(Collections.singleton("b")) 刪除所有指定元素newSetFromMap(Map<E,Boolean>):Map → Set 視圖asLifoQueue(Deque):Deque → 後進先出 QueuenCopies(n, o):返回包含 n 個相同引用的不可修改 ListunmodifiableXxx()UnmodifiableCollection 實現 Collection,構造器檢查 null,迭代器 remove() 拋異常checkedXxx()List<Integer> list = new ArrayList<>(); list.add("str"); // 編譯通過,運行不報錯Collections.checkedList(list, Integer.class) 包裝後,add("str") 拋 ClassCastExceptionCheckedCollection 在 add 時調用 typeCheck() 驗證 type.isInstance(o)synchronizedXxx()synchronized(this) 鎖,粗粒度同步java.util.concurrent 並發容器 (ConcurrentHashMap, CopyOnWriteArrayList 等)| 維度 | 適配器 | 裝飾器 |
|---|---|---|
| 目的 | 介面轉換:將 A 介面適配為 B 介面 | 行為增強:保持介面,動態添加職責 |
| Collections 例 | emptyList、singleton、newSetFromMap | unmodifiable、checked、synchronized |
| 核心類結構 | 實現目標介面,內部持有被適配對象 | 實現目標介面,內部持有被裝飾對象 |
| 是否可疊加 | 通常單層 | 支持多層疊加 (如 synchronized + unmodifiable) |
Collections.emptyList() (唯讀) / new ArrayList<>() (可寫)Collections.singleton(x)unmodifiableXxx()checkedXxx(list, Type.class)synchronizedXxx();高併發 → 並發包容器