比较来自世界各地的卖家的域名和 IT 服务价格

更改作为方法参数发送的数组

假设我有一个intrall,我想改变它。 我知道我无法分配作为参数发送的新阵列数组:


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//

, 只需复制值,而不是链接。 你能向我解释一下吗?

EDIT:

有没有方法可以在不改变链接的情况下将数组复制到对象中? 我的意思是制定打印的最后一个例子
2

.
已邀请:

风见雨下

赞同来自:

在你的方法中


public static void method/int[] n/



n

- 它是以这种方式传输的数组的另一个名称。 它在内存中指向同一个地方,作为一个数组的原始位置 ints. 如果更改存储在此阵列中的一个值,则指示它将看到此更改的所有名称。

但是,在方法本身


public static void method/int[] n/ {
int[] temp = new int[]{2};
n = temp.clone//;
}


您创建一个新数组,然后说: "姓名 'n' 现在表示此,另一个数组,而不是传输的那个". 实质上,名称 'n' 不再是传输的数组的名称。

快网

赞同来自:

你的例子 1 和 3 在问题的背景下几乎相同 - 您正在尝试分配新的含义
n

/这是对由值传输的数组的引用/.

你克隆了一个数组的事实
temp

, 无关紧要 - 他所做的一切,它创造了一份副本
temp

, 然后处方了
n

.

要将值复制到传输到您的方法的数组中
method

, 你可以看:
http://download.oracle.com/jav ... bject,%20int,%20java.lang.Object,%20int,%20int%29
当然,这一切都取决于阵列的大小
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
}

快网

赞同来自:

如您所注意到的,您无法将链接分配给作为参数传输的数组。 /或者,目的地在呼叫中没有任何影响。/

这是你能做的最好的事情:


public static void method/int[] n/ {
int[] temp = new int[]{2};
for /int i = 0; i < temp.length; i++/ {
n[i] = temp[i];
}
// ... or the equivalent using System.arraycopy/.../ or some such
}


当然,只有当输入数组的大小与您复制到它的数组的大小重合时,它才能正确工作。 /您如何应对这一点,取决于具体应用程序 .../

用于录音 Java 通过值传输对数组的引用。 它不会按值传输数组的内容。 克隆不会有助于解决这个问题。 /至少不是宣布的签名方法。/

知食

赞同来自:

在你的方法中
method

你分配的一无所有
n

, 永远不要更改传输和指定的对象的值
n

. 在一开始
method

,
n

表示阵列。 当你分配时
n

等于另一个数组,您只需重新指示哪个数组指示
n

, 并且不要改变任何事情
temp_array

从方法中
main

.

要回复问题请先登录注册