以下測試類別展示如何使用泛型 Queue<Integer>,並驗證自動裝箱特性:
package com.heatonresearch.examples.collections;
public class TestQueue {
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>();
queue.push(1);
queue.push(2);
queue.push(3);
try {
System.out.println("Pop 1: " + queue.pop());
System.out.println("Pop 2: " + queue.pop());
System.out.println("Pop 3: " + queue.pop());
} catch (QueueException e) {
e.printStackTrace();
}
}
}
關鍵點:
Queue<Integer> 限定只接受 Integer 物件,編譯期保證型別安全。1、2、3 等 int 基本型別時,J2SE 5.0 自動裝箱 為 Integer 物件。pop() 拋出 QueueException 表示佇列為空,需捕獲處理。1, 2, 3 驗證 FIFO(先進先出)行為。實作一個 PeekableStack(先進後出 FILO),支援:
push() / pop() 操作。Iterable 介面)。ConcurrentModificationException。public class PeekableStack<T> implements Iterable<T> {
private final List<T> list = new ArrayList<T>();
private int version = 0; // 版本號,用於偵測並發修改
public void push(T item) {
list.add(item);
version++; // 結構變更,版本號遞增
}
public T pop() {
int last = list.size() - 1;
if (last < 0) return null; // 空堆疊
T result = list.get(last);
list.remove(last);
version++;
return result;
}
@Override
public Iterator<T> iterator() {
return new PeekableStackIterator(this, list);
}
// 內部類別:標準 Iterator 實作
private static class PeekableStackIterator<T> implements Iterator<T> {
private final PeekableStack<T> stack;
private final List<T> snapshot;
private final int expectedVersion;
private int cursor = 0;
PeekableStackIterator(PeekableStack<T> stack, List<T> list) {
this.stack = stack;
this.snapshot = new ArrayList<T>(list); // 複製快照
this.expectedVersion = stack.version;
}
@Override
public boolean hasNext() {
checkModification();
return cursor < snapshot.size();
}
@Override
public T next() {
checkModification();
return snapshot.get(cursor++);
}
@Override
public void remove() {
throw new UnsupportedOperationException("不支援透過迭代器移除");
}
private void checkModification() {
if (stack.version != expectedVersion) {
throw new ConcurrentModificationException("迭代期間堆疊被修改");
}
}
}
}
| 機制 | 實作方式 | 目的 |
|---|---|---|
泛型參數 <T> | 類別宣告 PeekableStack<T> | 型別安全,適用任意物件型別 |
| for-each 支援 | 實作 Iterable<T>,提供 iterator() | 語法糖:for (T item : stack) |
| 並發修改檢測 | version 計數器 + 迭代器快照比對 | 防止迭代過程中結構變更導致不可預期行為 |
| 窺視功能 | 迭代器遍歷內部列表快照 | 不改變堆疊狀態下檢視所有元素 |
PeekableStack<String> stack = new PeekableStack<String>();
stack.push("A");
stack.push("B");
stack.push("C");
// for-each 窺視(不移除)
for (String s : stack) {
System.out.println("Peek: " + s); // 輸出 C, B, A (頂部優先)
}
// 標準 pop
while (!stack.isEmpty()) {
System.out.println("Pop: " + stack.pop()); // C, B, A
}
總結:透過泛型、Iterable、版本號檢測與快照迭代器,PeekableStack 實現了型別安全、可窺視、並發安全的現代化堆疊集合,完美融入 J2SE 5.0 集合生態。