【发布时间】:2021-08-05 12:12:27
【问题描述】:
public class Node<T> {
T data;
Node<T> next;
Node(T data){
this.data = data;
}
}
public class LinkedListUse{
public static void print(Node<Integer> head){
Node<Integer> temp = head;
while(temp != null){
System.out.print(temp.data +" ");
temp = temp.next;
}
System.out.println();
}
public static void increment(Node<Integer> head){
Node<Integer> temp = head;
while(temp != null){
temp.data++;
temp = temp.next;
}
}
public static void main(String args[]){
Node<Integer> node1 = new Node<Integer>(10);
Node<Integer> node2 = new Node<Integer>(20);
node1.next = node2;
increment(node1);
print(node1);
}
}
由于node1 在函数increment 中通过值传递(而不是通过引用传递),因此根据我的输出应该是10 20,但解决方案是11 21。
你能帮我解释一下这背后的原因吗
【问题讨论】:
-
在Java中,一切都是按值传递的,但是传递的是什么值呢?在对象的情况下是参考。所以很明显,当有引用时,对象的属性是可以改变的。
-
非常一般的建议:这类问题通常通过放置程序的中间输出来解决。在代码中间添加
System.out.println(...),看看发生了什么。 -
@LuisA.Florit:如果混淆是关于传递引用的确切性质,那只会加深混淆。他们必须尝试纠正他们对传递引用本质的误解(并且重复的问题有一些很好的答案可以帮助解决这个问题)。
标签: java data-structures linked-list output singly-linked-list