修改作为method-parameter传递的数组 [英] Modify an array passed as a method-parameter
问题描述
假设我有一个int数组,我想修改它。我知道我不能将新数组分配给作为参数传递的数组:
Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:
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()
:
Then, I tried to assign an arbitrary array to the array passed as parameter using 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()
复制数组,它只是复制值而不是引用。你可以帮我解释一下吗?
Now, I wonder why it prints 1 in last example while I'm just copying the array with clone()
which it's just copying the value not the reference. Could you please explain that for me?
编辑:有没有办法复制一个数组到对象而不更改引用?我的意思是让最后一个例子打印 2
。
Is there a way to copy an array to object without changing the reference? I mean to make last example printing 2
.
推荐答案
你的例子1在问题的上下文中,3和几乎是相同的 - 您正在尝试为 n
分配一个新值(这是对按值传递的数组的引用)。
Your examples 1 and 3 are virtually the same in context of the question - you are trying to assign a new value to n
(which is a reference to an array passed by value).
您克隆 temp
数组的事实并不重要 - 所有这一切都是创建<$的副本c $ c> temp 然后将其分配给 n
。
The fact that you cloned temp
array doesn't matter - all it did was create a copy of temp
and then assign it to n
.
为了将值复制到传递到方法
方法的数组中,您可能需要查看: System.arraycopy
In order to copy values into array passed into your method
method you might want to look at:System.arraycopy
这一切当然取决于你的的大小n
数组和您在方法
方法中创建的数组。
It all, of course, depends on the sizes of your n
array and the one you create inside method
method.
假设它们都有相同的长度,例如,你会这样做:
Assuming they both have the same length, for example, you would do it like that:
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
}
这篇关于修改作为method-parameter传递的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!