数组值传递

public class Test {
    public static void main(String[] args) {
        int[] array = { 1, 3, 5 }; 
        method(array); 
        for (int i = 0; i < array.length; i++) { // 循环输
            System.out.println(array[i]);
        }
    }
    public static void method(int[] x) { 
        int[] array = { 6, 3, 5 }; 
        x = array;
    }
}

结果:

1
3
5
public class Test {
    public static void main(String[] args) {
        int[] array = { 1, 3, 5 }; 
        method(array); 
        for (int i = 0; i < array.length; i++) { // 循环输
            System.out.println(array[i]);
        }
    }
    public static void method(int[] x) { 
        x[0] = 6; 
    }
}

结果:

6
3
5

我们来看一下第二种其执行时的内存状态:

4444657-64bcdea6fc93619e.png

如果是第一种方法,那么x[]指向的就不是main方法里面的数组,自然main方法里面的数组的值也不会变。

猜你喜欢

转载自blog.csdn.net/weixin_33829657/article/details/86810784