泛型的應(yīng)用——容器類

一個堆棧類

LinkList本身已經(jīng)具備了創(chuàng)建堆棧所必需的方法,而Stack本身可以通過兩個泛型類Stack<T>LinkedList<T>的組合創(chuàng)建。

我們可以不使用LinkList,來實(shí)現(xiàn)自己的內(nèi)部鏈?zhǔn)酱鎯C(jī)制。

public class LinkedStack<T> {
    private static class Node<U> {
        U item;
        Node<U> next;

        public Node() {
            item = null;
            next = null;
        }

        public Node(U item, Node<U> next) {
            this.item = item;
            this.next = next;
        }

        boolean end() {
            return item == null && next == null;
        }
    }

    private Node<T> top = new Node<>();

    public void push(T item) {
        top = new Node<>(item, top);
    }

    public T pop() {
        T result = top.item;
        if (!top.end()) {
            top = top.next;
        }
        return result;
    }

    public static void main(String[] args) {
        LinkedStack<String> lls = new LinkedStack<>();
        for (String s : "Phasers on stun!".split(" ")) {
            lls.push(s);
        }
        String s;
        while ((s = lls.pop()) != null) {
            System.out.println("s = " + s);
        }
    }
}
// Outputs
s = stun!
s = on
s = Phasers

內(nèi)部類Node也是一個泛型,它也擁有自己的類型參數(shù)。
這個例子用到了末端哨兵,在堆棧的最底部創(chuàng)建一個itemnext都為空的對象,如果堆棧已經(jīng)只剩末端哨兵,那么將不在移動取值。

RandomList

作為容器的另一個例子,假設(shè)我們需要一個持有特定類型對象的列表,每次調(diào)用其select()方法的時候,可以隨機(jī)選取一個元素,并且希望構(gòu)建一個可以運(yùn)用于各種類型的對象的工具,那么就應(yīng)當(dāng)泛型。

public class RandomList<T> {
    private ArrayList<T> storage = new ArrayList<>();
    private Random rand = new Random(47);

    public void add(T item) {
        storage.add(item);
    }

    public T select() {
        return storage.get(rand.nextInt(storage.size()));
    }

    public static void main(String[] args) {
        RandomList<String> rs = new RandomList<>();
        for (String s : ("The quick brown fox jumped over " + "the lazy brown dog").split(" ")) {
            rs.add(s);
        }
        for (int i = 0; i < 11; i++) {
            System.out.print(rs.select() + " ");
        }
    }
}
// Outputs
brown over fox quick quick dog brown The brown lazy brown 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本章將會介紹 泛型所解決的問題泛型函數(shù)類型參數(shù)命名類型參數(shù)泛型類型擴(kuò)展一個泛型類型類型約束關(guān)聯(lián)類型泛型 Where...
    寒橋閱讀 714評論 0 2
  • Swift泛型介紹 泛型是為Swift編程靈活性的一種語法,在函數(shù)、枚舉、結(jié)構(gòu)體、類中都得到充分的應(yīng)用,它的引入可...
    Bobby0322閱讀 14,268評論 0 26
  • 泛型(Generics) 泛型代碼允許你定義適用于任何類型的,符合你設(shè)置的要求的,靈活且可重用的 函數(shù)和類型。泛型...
    果啤閱讀 760評論 0 0
  • 泛型代碼可以確保你寫出靈活的,可重用的函數(shù)和定義出任何你所確定好的需求的類型。你的可以寫出避免重復(fù)的代碼,并且用一...
    iOS_Developer閱讀 886評論 0 0
  • 早睡早起 鍛煉 控制使用網(wǎng)絡(luò)時間 Remember the Final target For myself For...
    TNANNAN閱讀 276評論 0 0

友情鏈接更多精彩內(nèi)容