Java中的数组分配和参考 [英] Array assignment and reference in Java
问题描述
public class Test {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = a;
int[] c = {6, 7, 8};
a = c;
for(int i = 0; i < a.length; i ++)
System.out.print(a[i] + " ");
System.out.print("\n");
for(int i = 0; i < b.length; i ++)
System.out.print(b[i] + " ");
System.out.print("\n");
}
}
我已经初始化了数组a,并将a的引用分配给新数组b.现在,我初始化了一个新的数组c并将其引用传递给数组a.由于数组b是对数组a的引用,因此b应该具有c中的新值,但是b具有a的旧值.背后的原因是什么? 输出在下面给出-
I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -
输出-
6 7 8
1 2 3 4 5
推荐答案
不要被名称"list"所打扰.图像取自python可视化,但是原理在Java中是相同的
数组a
被分配了一个新数组:
Array a
is assigned with a new array:
将数组b
分配给a
之后的实例:
Array b
is assigned to the instance behind a
:
数组c
被分配了一个新数组:
Array c
is assigned with a new array:
最后将a
分配给c
之后的实例,b
未被重新分配,并且仍然保留对旧a
的引用:
And finally a
is assigned to the instance behind c
, b
was not re-assigned and still keeps a reference to the old a
:
图像取自pythontutor.com上的可视化图像
这篇关于Java中的数组分配和参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!