一個堆棧類
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)建一個item和next都為空的對象,如果堆棧已經(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