Java中将数组分配给其他数组的问题 [英] Problem with assigning an array to other array in Java
问题描述
public class TestingArray {
public static void main(String[] args) {
int iCheck = 10;
int j = iCheck;
j = 11;
System.err.println("value of iCheck "+iCheck);
int[] val1 = {1,2,9,4,5,6,7};
int[] val2 = val1;
val2[0] = 200;
System.err.println("Array Value "+val1[0]);
}
}
输出:
iCheck 10 的价值
数组值 200
从上面的代码中,我发现如果任何数组 val2
被分配给另一个数组 val1
并且如果我们更改 val2
的任何值> 数组,结果同样反映在数组 val1
上,而相同的场景不是变量赋值.为什么?
From the above code, I found that if any array val2
is being assigned to another array val1
and if we change any value of val2
array, the result is as well reflected for the array val1
while the same scenario is not with variable assignment.
Why?
推荐答案
以下语句使 val2
引用与 val1
相同的数组:
The following statement makes val2
refer to the same array as val1
:
int[] val2 = val1;
如果要复制,可以使用 val1.clone()
或 Arrays.copyOf()
:
If you want to make a copy, you could use val1.clone()
or Arrays.copyOf()
:
int[] val2 = Arrays.copyOf(val1, val1.length);
对象(包括集合类的实例、String
、Integer
等)以类似的方式工作,将一个变量分配给另一个变量只是简单地复制引用,使两者都变量引用同一个对象.如果所讨论的对象是可变的,那么通过其中一个变量对其内容所做的后续修改也将通过另一个变量可见.
Objects (including instances of collection classes, String
, Integer
etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.
原始类型(int
、double
等)表现不同:不涉及引用并且赋值会复制值.
Primitive types (int
, double
etc) behave differently: there are no references involved and assignment makes a copy of the value.
这篇关于Java中将数组分配给其他数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!