Java 使用泛型實現堆疊類
阿新 • • 發佈:2019-01-27
Java中泛型的一個主要作用就是創造容器類。這裡結合泛型實現一個堆疊類。
LinkedStack.java
/**
*LinkedList:java實現內部鏈式儲存機制
*/
public class LinkedStack<T> {
/**棧頂元素 */
private Node<T> top = new Node<T>();
/**
* 彈出棧頂元素
*/
public T pop() {
//彈出棧頂的元素;
T result = top.item;
//如果不是棧底,就把棧頂指向下一個元素
if(!top.end())
top = top.next;
return result;
}
/**
* 壓入棧
*/
public void push(T item){
top = new Node<T>(item, top);
}
/**
*Node
*/
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;
}
}
public static void main(String args[]) {
LinkedStack<String> lss = new LinkedStack<String> ();
for(String s : "Sunpro is singing !".split(" "))
lss.push(s);
String s;
while((s = lss.pop()) != null)
System.out.println(s);
LinkedStack<Integer> lst = new LinkedStack<Integer>();
int[] test = {1,2,3,4,5};
for(int i : test)
lst.push(i);
Integer a = 0;
while((a = lst.pop()) != null)
System.out.println(a);
}
}
執行結果:
!
singing
is
Sunpro
5
4
3
2
1
可以看出執行結果符合棧“先入後出”的特點。
需要特別說明的是,在列印第二個堆疊即lst時,我本來用的int a = 0;結果編譯時報錯,
“LinkedStack.java:57: 錯誤: 不可比較的型別: int和<空值>
while((a = lst.pop()) != null)
^
1 個錯誤”
這是個低階錯誤了,因為int是基本資料型別嘛,改為Integer 就可以了。
補充一下,上面強調的這個錯誤,不僅僅是我的錯誤,也體現出了Java泛型的一個侷限性:Java中基本資料型別不能做型別引數!
JavaSE5中,有自動打包和拆包功能,我們可以比較方便的將基本資料型別與其包裝器型別進行轉換。