集合框架是 Java 處理數據組的統一架構。本文系統總結數組與集合差異、Collection/Map 兩大體系、核心實現類特性、遍歷模式、工具類 Collections,附帶驗證代碼與輸出結果。
| 維度 | 數組 | 集合 |
|---|---|---|
| 元素類型 | 基本類型 + 引用類型 | 僅引用類型(基本類型自動裝箱) |
| 長度 | 固定 | 動態可變 |
| 功能豐富度 | 僅存取 | 豐富 API(增刪改查、遍歷、排序等) |
List<String> list = new ArrayList<>();
list.add("A"); list.add("B"); list.add("C");
list.addAll(0, Arrays.asList("1","2","3")); // [1,2,3,A,B,C]
List<String> sub = list.subList(1, 5); // [2,3,A,B] 左閉右開
list.set(3, "Set"); // 索引3 A→Set
list.indexOf("3"); // 2, indexOf("D"); // -1
String[] arr = list.toArray(new String[0]); // 轉數組
list.clear(); list.isEmpty(); // true
LinkedList<String> ll = new LinkedList<>();
ll.add("1"); ll.add("2"); ll.add("3");
ll.addFirst("F"); ll.addLast("L"); // [F,1,2,3,L]
// 獲取表頭方法對比
ll.getFirst(); // 拋異常如果空
ll.element(); // 拋異常如果空
ll.peek(); // 返回null如果空
ll.poll(); // 獲取並移除,空返回null
ll.pop(); // 同poll,棧語義
// FIFO 隊列演示
while (!ll.isEmpty()) System.out.print(ll.poll() + " "); // F 1 2 3 L
equals()/hashCode()Comparable 或提供 Comparatorclass Person implements Comparable<Person> {
String name; int age;
public int compareTo(Person o) {
int diff = this.age - o.age;
return diff != 0 ? diff : this.name.compareTo(o.name);
}
}
Set<Person> ts = new TreeSet<>();
ts.add(new Person("小強",21));
ts.add(new Person("小偉",23));
ts.add(new Person("小強",21)); // 重複不加入
ts.add(new Person("小琴",20));
ts.add(new Person("小婷",20));
// 輸出:小婷20, 小琴20, 小強21, 小偉23
Map<Integer, String> map = new HashMap<>();
map.put(1, "清華"); map.put(2, "北大"); ...
// 1. keySet + get (兩次查找)
for (Integer k : map.keySet()) System.out.println(k + "=" + map.get(k));
// 2. entrySet + Iterator
Iterator<Map.Entry<Integer,String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer,String> e = it.next();
System.out.println(e.getKey() + "=" + e.getValue());
}
// 3. entrySet + foreach (推薦)
for (Map.Entry<Integer,String> e : map.entrySet())
System.out.println(e.getKey() + "=" + e.getValue());
// 4. values (僅需值)
for (String v : map.values()) System.out.println(v);
功能同 HashMap,但 Key 保持升序,性能稍低。
所有方法均為 static,常用:
| 方法 | 用途 |
|---|---|
sort(List) | 自然序排序 |
sort(List, Comparator) | 定制序排序 |
binarySearch(List, key) | 二分查找(需先排序) |
reverse(List) | 反轉 |
shuffle(List) | 隨機打亂 |
max/min(Collection) | 極值 |
synchronizedList/List/Map/Set | 線程安全包裝 |
unmodifiableList/Map/Set | 不可變視圖 |
addAll(Collection, T...) | 批量添加 |
replaceAll(List, old, new) | 批量替換 |
集合選型決策樹:
需要 Key-Value → Map
├─ 高併發 → ConcurrentHashMap
├─ 需排序 → TreeMap
├─ 需插入序 → LinkedHashMap
└─ 一般 → HashMap
需要單列集合 → Collection
├─ 需去重 → Set
│ ├─ 需排序 → TreeSet
│ ├─ 需插入序 → LinkedHashSet
│ └─ 一般 → HashSet
└─ 允許重複 → List
├─ 隨機訪問多 → ArrayList
└─ 首尾增刪多 → LinkedList
掌握核心實現原理、API 特性、遍歷最佳實踐,是 Java 開發者的基本功。