可能重复:
Make copy of array Java
我是Java的初学者,我需要将一个数组的内容复制到另一个变量中。但是,Java总是通过引用而不是值传递数组。
如果这令人困惑,我的意思是:
int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
System.out.print(test[i]); // Prints 1284 instead of 1234
在此示例中,我不希望更改test
的值。如果不使用Java的任何更高级的功能,例如ArrayList和Vectors,这是否可行?
编辑:我尝试过System.ArrayCopy和test.clone(),但它们似乎仍无法正常工作。 这是我的实际代码:
temp_image=image.clone();
for(int a=0;a<image.length;a++)
for(int b=0;b<image[0].length;b++)
image[a][b]=temp_image[image.length-1-a][b];
基本上我试图翻转“图像”。代码中某处有错误吗?
答案 0 :(得分:5)
您需要克隆阵列。
test2=test.clone();
答案 1 :(得分:2)
从Java 6开始,您可以使用Arrays.copyOf:
test2 = Arrays.copyOf(test, test.length);
对于你要做的事情,test.clone()很好。但是如果你想做一个调整大小,copyOf允许你这样做。我认为就性能而言
如果您需要,System.arraycopy会提供更多选择。
答案 2 :(得分:0)
因为test和test2都是指向同一个数组的指针,所以您要使用语句test
test2
和test2[2]=8
的值
解决方案是将test的内容复制到test 2中,并在test2的特定索引处更改值。
for (int i=0,i<test.length,i++)
test2[i]=test[i]
//Now both arrays have the same values
test2[2]=8
for (int j=0,j<test.length,j++)
System.out.print(test[i])
System.out.println()
System.out.print(test2[i])
将输出
1 2 3 4
1 2 8 4