假设我有一个整数数组,我想修改它。我知道我无法将新数组分配给作为参数传递的数组:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1
}
public static void method(int[] n)
{
n = new int[]{2};
}
虽然我可以修改它:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 2
}
public static void method(int[] n)
{
n[0] = 2;
}
然后,我尝试使用 clone()
将任意数组分配给作为参数传递的数组:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1 ?!
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
n = temp.clone();
}
现在,我想知道为什么它在上一个示例中打印 1 而我只是使用 clone()
复制数组,它只是复制值而不是引用。你能为我解释一下吗?
编辑:有没有办法在不更改引用的情况下将数组复制到对象?我的意思是让最后一个例子打印 2
。
最佳答案
您的示例 1 和 3 在问题的上下文中几乎相同 - 您正在尝试为 n
分配一个新值(这是对按值传递的数组的引用)。
克隆 temp
数组的事实并不重要 - 它所做的只是创建 temp
的副本,然后将其分配给 n
。
为了将值复制到传入您的 method
方法的数组中,您可能需要查看:System.arraycopy
当然,这一切都取决于您的 n
数组的大小以及您在 method
方法中创建的数组的大小。
例如,假设它们的长度相同,您可以这样做:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]);
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
System.arraycopy(temp, 0, n, 0, n.length);
// or System.arraycopy(temp, 0, n, 0, temp.length) -
// since we assumed that n and temp are of the same length
}
关于java - 修改作为方法参数传递的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7129369/