public class StackWithLinkedList<P> {
private Node top = null;
public StackWithLinkedList(){}
public void push(P val){
Node newNode = new Node(val);
if (this.top != null) {
newNode.nextLink = top;
}
this.top = newNode;
}
public void traverse(){
Node currentNode = this.top;
while(currentNode != null){
System.out.println(currentNode.val);
currentNode = currentNode.nextLink;
}
}
private class Node{
Node nextLink;
P val;
public Node(P val){
this.val = val;
}
}
}
看看traverse()中的这段代码,
Node currentNode = this.top;
这里创建了一个 Node 类型的对象,它指向已经存在的this.top节点对象。
所以这意味着,两个引用指向内存中的同一个对象不是吗?
但是当我使用 traverse() 方法时,两个对象都独立工作,因为 currentNode 在遍历后变为 Null 但 this.top 保持不变,保留所有已推送的节点。
我尝试调试,我看到 this.top 与 currentNode 具有相同的内存地址。
到底,
我无法弄清楚为什么会这样?