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

J2SE 5.0 自訂泛型集合實戰:Queue 測試與 PeekableStack 實作

     編輯:J2SE

泛型 Queue 測試驗證

以下測試類別展示如何使用泛型 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),支援:

  1. 標準 push() / pop() 操作。
  2. 可窺視:在不移除元素前提下遍歷堆疊內容。
  3. 支援 J2SE 5.0 for-each 迴圈(需實作 Iterable 介面)。
  4. 並發修改檢測:迭代期間若結構被修改,拋出 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 集合生態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved