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中,有自动打包和拆包功能,我们可以比较方便的将基本数据类型与其包装器类型进行转换。