我有一个使用“ListNode”类对象的链表
ListNode有以下非静态方法:
getValue()
setValue(Object obj)
getNext()
setNext(ListNode ln)
它的构造函数接受一个值和一个下一个值。
在我的驱动程序类的主要方法中,创建我的链接列表:
ListNode head = new ListNode("Overflow!", null);
head = new ListNode("Stack", head);
head = new ListNode("in", head);
head = new ListNode("is", head);
head = new ListNode("This", head);
我有一个名为 printList(ListNode ln)
的方法。
我在主方法中连续调用它两次,如下所示:
printList(head);
System.out.println();
printList(head);
我的方法如下所示:
public static void printList(ListNode head)
{
while(head != null)
{
System.out.print(head.getValue()+" ");
head = head.getNext();
}
}
在我的方法中,每次在 while 循环中引用都会更改为指向不同的对象。所以在我退出该方法后,引用“head”应该指向空,对吧?然而,当第二次调用 printList(head) 时,它神奇地打印了列表中的所有元素!
这是 jGrasp 控制台显示的内容:
----jGRASP exec: java StackOverflowQuestionExampleClass
This is in Stack Overflow!
This is in Stack Overflow!
----jGRASP: operation complete.
这是我的老师告诉我使用的 listnode 类:
//Thomas Bettge, TJHSST, 10-20-2006
public class ListNode
{
private Object value;
private ListNode next;
public ListNode(Object v, ListNode n)
{
value=v;
next=n;
}
public Object getValue()
{
return value;
}
public ListNode getNext()
{
return next;
}
public void setValue(Object newv)
{
value=newv;
}
public void setNext(ListNode newn)
{
next=newn;
}
}
最佳答案
困惑可能源于以下事实:您有 2 个具有相同名称“head”的标签。 printList 方法中的“head”参数是对传入对象的新引用。重新分配它不会影响原始引用的目标(从某种意义上说,不会导致它引用其他内容。旁白:对引用对象的状态的更改将会产生影响,因为它是同一个对象,无论引用它的是什么。
这样查看您的代码可能会更清楚:
public void yourMainMethod() {
ListNode head = new ListNode("Overflow!", null);
head = new ListNode("Stack", head);
head = new ListNode("in", head);
head = new ListNode("is", head);
head = new ListNode("This", head);
printList(head);
System.out.println();
printList(head);
}
//note different name, to clarify this is a separate reference
public static void printList(ListNode node) {
while(node != null)
{
System.out.print(node.getValue()+" ");
node = node.getNext();
//node.setValue(new Object());//note that this would change the state inside the ListNode passed in
}
}
关于java - 在方法中重新分配引用是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214422/