首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Collection vs Collections:一字之差,天壤之別

     編輯:Java 相關知識

核心區別一覽

維度Collection (介面)Collections (工具類)
類型頂層集合介面final 工具類
定義位置java.util.Collectionjava.util.Collections
實例化多態引用具體實現(ArrayList、HashSet 等)私有構造器,**不可實例化**
核心職責定義集合通用契約(增刪改查、遍歷、大小)提供靜態工具方法(排序、查找、同步包裝、不可變視圖)
方法類型實例方法全部 static 方法

Collection 介面體系


Collection (介面)
├── List (有序、可重複)
│   ├── ArrayList (動態陣列、隨機訪問快)
│   ├── LinkedList (雙向鏈表、首尾增刪快)
│   └── Vector (同步、legacy)
│       └── Stack (LIFO、legacy)
├── Set (無序、不可重複)
│   ├── HashSet (HashMap 底層、O(1) 查找)
│   ├── LinkedHashSet (維護插入順序)
│   └── TreeSet (紅黑樹、有序、O(log n))
└── Queue (佇列)
    ├── PriorityQueue (堆、優先級)
    ├── ArrayDeque (雙端佇列、非同步)
    └── BlockingQueue (阻塞佇列介面)
        ├── ArrayBlockingQueue
        ├── LinkedBlockingQueue
        └── ...

Map 不繼承 Collection,但提供 keySet()、values()、entrySet() 返回 Collection 視圖。

Collections 工具類核心功能

1. 排序與查找


List<Integer> list = Arrays.asList(3, 1, 4, 1, 5);
Collections.sort(list);                    // 自然順序 [1, 1, 3, 4, 5]
Collections.sort(list, Comparator.reverseOrder()); // 降序 [5, 4, 3, 1, 1]

int idx = Collections.binarySearch(list, 3); // 前提:已排序,返回索引 2

2. 集合操作


Collections.shuffle(list);                 // 隨機打亂
Collections.reverse(list);                 // 反轉
Collections.rotate(list, 2);               // 循環右移 2 位
Collections.swap(list, 0, 4);              // 交換索引 0 和 4
Collections.fill(list, 99);                // 全部替換為 99
Collections.copy(dest, src);               // 複製(dest 長度 ≥ src)
Collections.replaceAll(list, 1, 9);        // 所有 1 替換為 9

3. 極值與統計


int max = Collections.max(list);           // 最大值
int min = Collections.min(list);           // 最小值
int freq = Collections.frequency(list, 1); // 元素 1 出現次數
boolean disjoint = Collections.disjoint(list1, list2); // 無交集

4. 同步包裝(舊版線程安全,現代首選 java.util.concurrent)


List<String> syncList = Collections.synchronizedList(new ArrayList<>());
Set<String> syncSet = Collections.synchronizedSet(new HashSet<>());
Map<K, V> syncMap = Collections.synchronizedMap(new HashMap<>());

// 迭代時必須手動同步!
synchronized (syncList) {
    for (String s : syncList) { /* ... */ }
}

5. 不可變視圖(防禦性編程)


List<String> unmod = Collections.unmodifiableList(originalList);
Set<String> unmodSet = Collections.unmodifiableSet(originalSet);
Map<K, V> unmodMap = Collections.unmodifiableMap(originalMap);

// 嘗試修改拋出 UnsupportedOperationException
// unmod.add("x"); // 運行時異常

6. 空集合單例(避免分配空對象)


List<String> emptyList = Collections.emptyList();     // 不可變空列表
Set<String> emptySet = Collections.emptySet();
Map<K, V> emptyMap = Collections.emptyMap();
// 等價於 List.of() (JDK 9+),但兼容舊版本

7. 單例集合


List<String> singleton = Collections.singletonList("only");
Set<String> singletonSet = Collections.singleton("only");
Map<K, V> singletonMap = Collections.singletonMap("key", "value");

現代替代:JDK 9+ 集合工廠方法


// 不可變集合一行創建
List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("a", "b", "c");
Map<String, Integer> map = Map.of("a", 1, "b", 2);
Map<String, Integer> map10 = Map.ofEntries(
    Map.entry("a", 1), Map.entry("b", 2) /* ... */);

// 可變集合仍需 new ArrayList<>(List.of(...))

常見誤區

  1. 以為 Collections 是 Collection 父類:完全無繼承關係,一個介面、一個工具類
  2. 直接遍歷同步包裝集合不加鎖:必須在同步塊中迭代
  3. 以為 unmodifiableList 就是不可變集合:它是視圖,底層原集合修改會反映到視圖。真正不可變用 List.copyOf() 或 List.of()
  4. Collections.sort() 修改原列表:原地排序,非返回新列表。需保留原順序請先複製

速查表:何時用哪個?

需求使用
聲明集合變量、參數、返回類型Collection / List / Set 介面
創建具體集合對象new ArrayList<>()、List.of()
排序、打亂、二分查找、極值Collections.sort() 等靜態方法
線程安全包裝(舊代碼維護)Collections.synchronizedXxx()
對外暴露只讀視圖Collections.unmodifiableXxx() 或 List.copyOf()
返回空集合避免 nullCollections.emptyList() / List.of()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved