我想让两个数组具有相同的值 [英] I want to have two arrays to have the same values
本文介绍了我想让两个数组具有相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java中将 array2
设置为 array1
,如下所示,但这不起作用.
I want to set array2
to array1
in Java alike below but it doesn't work.
int[] array1 = new int[3]{1,2,3};
int[] array2 = new int[3];
array2 = array1;
这有什么问题?
推荐答案
将 array1
的引用分配给 array2
时,会创建一个 shallow 数组的副本;这两个引用指向同一数组.我假设您想要一个 deep 副本,并且可以使用
When you assign the reference of array1
to array2
you create a shallow copy of the array; the two references point to the same array. I assume you wanted a deep copy and you can use Arrays.copyOf(int[], int)
to get one. Also, you don't need new[]
and an explicit size. That could look something like
int[] array1 = { 1, 2, 3 };
int[] array2 = Arrays.copyOf(array1, array1.length);
这篇关于我想让两个数组具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文