泛型的应用——容器类

2017-09-09  本文已影响10人  呆呆李宇杰

一个堆栈类

LinkList本身已经具备了创建堆栈所必需的方法,而Stack本身可以通过两个泛型类Stack<T>LinkedList<T>的组合创建。

我们可以不使用LinkList,来实现自己的内部链式存储机制。

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

内部类Node也是一个泛型,它也拥有自己的类型参数。
这个例子用到了末端哨兵,在堆栈的最底部创建一个itemnext都为空的对象,如果堆栈已经只剩末端哨兵,那么将不在移动取值。

RandomList

作为容器的另一个例子,假设我们需要一个持有特定类型对象的列表,每次调用其select()方法的时候,可以随机选取一个元素,并且希望构建一个可以运用于各种类型的对象的工具,那么就应当泛型。

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 
上一篇 下一篇

猜你喜欢

热点阅读