为什么将java数组作为参数放在方法中会将其设置在方法之外?

ebdffaop  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(382)

当我不改变实际变量时,我很困惑为什么数组会被改变。这是一个示例,演示了如何对数组和int执行完全相同的操作,但得到不同的结果。

import java.util.Arrays;
public class example
{
    public static void main(String[] args)
    {
        int[] arrayInMain = {1,2,3,6,8,4};
        System.out.println("Original Value: " + Arrays.toString(arrayInMain));
        arrayMethod(arrayInMain);
        System.out.println("After Method Value: " + Arrays.toString(arrayInMain));
        int intInMain = 0;
        System.out.println("Original Value: " + intInMain);
        intMethod(intInMain);
        System.out.println("After Method Value: " + intInMain);
    }
    private static void arrayMethod(int[] array)
    {       
        int[]b = array;
        b[1] = 99;//Why does this not just set the local array? The array outside of this method changes
    }
    private static void intMethod(int i)
    {
        int j = i;
        i = 99;//This works normally with only the value of j being changed
    }
}

输出为:

Original Value: [1, 2, 3, 6, 8, 4]
After Method Value: [1, 99, 3, 6, 8, 4]
Original Value: 0
After Method Value: 0

为什么会这样?我是犯了一个愚蠢的错误,还是java数组就是这样工作的?
谢谢您!

jw5wzhpr

jw5wzhpr1#

正如@khelwood所说,您正在将引用传递给数组。通过更改引用,还可以更改java中的原始引用。如何创建可以使用的阵列的实际副本 Arrays.copyOf() ```
int[] arrayCopy = Arrays.copyOf(yourArray, yourArray.length);

相关问题