泛型适袜,實(shí)現(xiàn)了參數(shù)化類型的概念寸士。
2.簡(jiǎn)單泛型
有些情況下我們確實(shí)希望容器能夠同時(shí)持有多種類型的對(duì)象。但通常而言牵祟,我們只使用容器來存儲(chǔ)一種類型的對(duì)象深夯。泛型的主要目的就是用來指定容器要持有什么類型的對(duì)象,而且由編譯器來保證類型的正確性。
現(xiàn)在創(chuàng)建TDemo時(shí)咕晋,必須指明想持有什么類型的對(duì)象雹拄,將其置于尖括號(hào)內(nèi)。就像main()方法掌呜,然后就只能在TDemo中存入該類型的對(duì)象滓玖。取出持有對(duì)象時(shí),自動(dòng)就是正確的類型质蕉。
public class TDemo<T> {
private T a;
public TDemo(T a) {
this.a = a;
}
public void set(T a) {
this.a = a;
}
public T get() {
return a;
}
}
傳統(tǒng)的下推堆棧
使用末端哨兵來判斷堆棧何時(shí)為空势篡。這個(gè)末端哨兵是在構(gòu)建LinkedStack時(shí)創(chuàng)建的。然后模暗,每調(diào)用一次push()方法禁悠,就會(huì)創(chuàng)建一個(gè)Node<T>對(duì)象,并將其鏈接到前一個(gè)Node<T>對(duì)象兑宇。當(dāng)你調(diào)用pop()方法時(shí)碍侦,總是返回top.item,然后丟棄當(dāng)前top所指的Node<T>,并將top轉(zhuǎn)移到下一個(gè)Node<T>,除非你已經(jīng)碰到了末端哨兵,這時(shí)候就不再移動(dòng)top了隶糕。如果已經(jīng)到了末端瓷产,客戶端調(diào)用pop()方法,只能得到null枚驻,說明堆棧已經(jīng)空了 濒旦。
public class LinkedStack<T> {
private static class Node<U> {
U item;
Node<U> next;
Node() {
item = null;
next = null;
}
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<T>(); // End sentinel
public void push(T item) {
// System.out.println("push() before : " + top.item);
top = new Node<T>(item, top);
// System.out.println("push() after : " + top.item);
/**
* 正序進(jìn)來 倒序出去
* Node<T> top = new Node<T>(null) next為null item null
* Node<T> top1 = new Node<T>(top) next為top item Phasers
* Node<T> top2 = new Node<T>(top1) next為top1 item on
* Node<T> top3 = new Node<T>(top2) next為top2 item stun
*/
}
public T pop() {
T result = top.item;
if (!top.end()) {
top = top.next;
// System.out.println("pop() : " + top.item);
}
return result;
}
public static void main(String[] args) {
LinkedStack<String> lss = new LinkedStack<String>();
for (String s : "Phasers on stun!".split(" "))
lss.push(s);
String s;
while ((s = lss.pop()) != null)
System.out.println(s);
}
} /* Output:
stun!
on
Phasers
*///:~