【问题标题】:The array value changed after calling static method with the array Java [duplicate]使用数组Java调用静态方法后数组值发生了变化[重复]
【发布时间】:2021-01-15 09:56:25
【问题描述】:

调用静态方法时数组元素的值发生变化,参数传递与参数相同的数组,但原始值没有变化

当我们将数据结构作为方法参数传递时,它的工作方式是否不同? 想知道为什么在使用数组的方法调用后数组元素会发生变化.. 我在最后一个 syso 语句中期望值为 0 而不是 999

public class TestStatic {
    
    public static int square (int x)
    {
        x = x + 1;
        return x * x;       
    }

    public static int[] changeArr(int a[])
    {
        a[0] = 999;
        return a;
    }
    
    public static void main(String[] args)
    {
        int a = 10;

        System.out.println((square(a)));
        System.out.println(a);

        int arr[] = {0,0};
        changeArr(arr);
        System.out.println(arr[0]);
    }
}

实际输出:

121
10
999

我期待

121
10
0

【问题讨论】:

  • changeArr(arr) - arr 是对您在 main 方法中声明的数组的引用。由于您传递了对changeArr 方法的引用,因此当方法更改第一个索引处的值时,它会更改您在main 方法中声明的相同数组。
  • 可能,可以读作a[] 的签名是int 类型的,有点误导。将其更改为:public static int[] changeArr(int[] a) { ... } 并阅读:aint[] 类型的参数。所以它是一个对象,对象是按引用而不是按类型传递的。

标签: java arrays static-methods


【解决方案1】:

在 Java 中,方法参数是通过引用而不是通过值,这意味着您将引用传递给对象,而不是对象的副本。请注意,原语是按值传递的。

【讨论】:

  • 一切都是按值传递的。在对象的情况下,值是对对象的引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多