更改方法中的数组会更改数组外部 [英] Changing array in method changes array outside

查看:145
本文介绍了更改方法中的数组会更改数组外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的变量范围有问题。

public static void main(String[] args){
    int[] test={1,2,3};
    test(test);
    System.out.println(test[0]+" "+test[1]+" "+test[2]);
}

static void test(int[] test){
    test[0]=5;
}

我预计输出为 1 2 3 ,但结果是 5 2 3
为什么我在方法中更改了数组中的值,但原始数组发生了变化?

I expected the output to 1 2 3, but the result was 5 2 3. Why I changed the value in the array in the method, but the original array changed?

推荐答案

数组中的数组Java是一个对象。当您通过 new 创建数组时,它将在堆上创建,并返回一个引用值(类似于C中的指针)并将其分配给您的变量。

An array in Java is an object. When you create an array via new, it's created on the heap and a reference value (analogous to a pointer in C) is returned and assigned to your variable.

在C中,这表示为:

int *array = malloc(10 * sizeof(int));

当您将该变量传递给方法时,您传递的是已分配的参考值(已复制) )到方法中的本地(堆栈)变量。不复制数组的内容,只复制参考值。再次,就像将指针传递给C中的函数一样。

When you pass that variable to a method, you're passing the reference value which is assigned (copied) to the local (stack) variable in the method. The contents of the array aren't being copied, only the reference value. Again, just like passing a pointer to a function in C.

因此,当您通过该引用修改方法中的数组时,您正在修改单个数组对象存在于堆上。

So, when you modify the array in your method via that reference, you're modifying the single array object that exists on the heap.

您评论说您通过 int [] temp = test 制作了数组的副本...再次,这只会生成指向内存中单个数组的引用值(指针)的副本。你现在有三个变量都对同一个数组保持相同的引用(一个在你的 main()中,在你的方法中有两个)。

You commented that you made a "copy" of the array via int[] temp=test ... again, this only makes a copy of the reference value (pointer) that points to the single array in memory. You now have three variables all holding the same reference to the same array (one in your main(), two in your method).

如果要复制数组的内容,Java会提供 Arrays 类中的静态方法

If you want to make a copy of the array's contents, Java provides a static method in the Arrays class:

int[] newArray = Arrays.copyOf(test, test.length); 

这会在堆上分配一个新的数组对象(由第二个参数指定的大小),副本现有数组的内容,然后返回对该新数组的引用。

This allocates a new array object on the heap (of the size specified by the second argument), copies the contents of your existing array to it, then returns the reference to that new array to you.

这篇关于更改方法中的数组会更改数组外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆