一个小的Stack的Java示例图解分析(例子来自《Java编程思想(第四版)》)
介绍
最近我在学习Java泛型的相关知识。不经意间看到了这个示例,然后就产生了弄明白这个栈push,pop,初始化时到底发生了什么。
以下都是我的个人理解,如有谬误,敬请指正!
另外,这篇博客还有个英文版,来自我的github博客。我的github名字是aerexu,所以你应该知道怎么找到我的英文博客了。
Code
首先,代码来自于《Java编程思想(第四版)》的357页,第15章。
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<>();
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> lss = new LinkedStack<>();
for(String s : "Phasers on stun!".split(" "))
lss.push(s);
String s;
while ((s=lss.pop())!=null)
System.out.println(s);
}
}
// The result is
// stun!
// on
// Phasers
分析
显然, 类型U 就是 T, 而且在这个例子里面是 String 。 这是由对内部静态类的两个方法调用决定的 private Node<T> top = new Node<>();
和 top = new Node<>(item, top);
. 示例中关于泛型的所有知识点都在这了。
模型
让我用下图来展示Node和LinkedStack的实例(instance)。
创建stack
当我们new了这个lss后,你会得到一个完全为空的stack。图中的 Pn 是Node的引用,这个Node是new Node<T>()
创建的实例。
Push
接着让我们调用 void push(T item)
两次, 第一次push a ,第二次push b . 注意: 引用 pa 和 pb 是在调用 new Node<T>(item,top)
后生成的.
Pop
然后调用 T pop()
两次, 来看看 b 和 a 怎么pop出来的. 注意: lss 利用 next ( 第一次 pop()
为pb , 第二次 pop()
为pa) 来拿到真正的 Node.