【发布时间】:2011-10-31 01:23:10
【问题描述】:
假设我有一个 int 数组并且我想修改它。我知道我不能将新数组分配给作为参数传递的数组:
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。
【问题讨论】:
标签: java arrays clone pass-by-value