为什么当我创建一个链表节点,附加一些数据,然后在另一个方法中移动头部,头部在被调用方法中保持不变?
例如:public static void append(Node n, int d) {
while (n.next != null) {
n = n.next;
}
n.next = new Node(d);
}
public static void test(Node n) {
n = n.next;
}
public static void main(String[] args) {
Node head = new Node(5);
append(head, 4);
append(head, 3);
test(head); //this moves the head to head.next
//why is head still = 5 after we get here?
}
在方法append
中,行n = n.next
不会影响作为参数传递的原始节点,在您的示例中为head
。为什么?因为Java是通过值传递的。这意味着,如果在方法内部修改head
的引用(在方法内部被接收为n
),它不会影响原始引用。因此,head
将仍然引用内存中的相同位置(相同的对象)。
test
没有做任何事情,因为你正在创建一个局部变量:
Node next = ...;
,然后给它赋值n.next
。但是这个变量只存在于那个方法内部,所以它不会影响它外部的任何东西。
next
是一个属性,不是一个方法。您的test
方法只是抓取对n.next
的引用,它不是"移动头部"。