Arrays – 通过引用调用

huangapple go评论118阅读模式
英文:

Arrays - Call by reference

问题

在Java中将一个数组传递给函数,然后将其赋值给一个新数组,我得到的仍然是同样的旧数组。

public static void main(String[] args) {
    int[] arr1 = { 1, 2, 3, };
    changes(arr1);
    for (int val : arr1) {
        System.out.println(val);
    }
}

private static void changes(int[] arr1) {
    int[] arr2 = { 7, 8, 9 };
    arr1 = arr2;
}

为什么在传递数组时会涉及传递对该数组的引用呢?

英文:

While passing an array to a function in java and then assigning it to a new array, I am getting the same old array.

public static void main(String[] args) {
		int[] arr1 = { 1, 2, 3, };
		changes(arr1);
		for (int val : arr1) {
			System.out.println(val);
		}
	}

private static void changes(int[] arr1) {
	int[] arr2 = { 7, 8, 9 };
	arr1 = arr2;
}

Why is it so when passing array deals with passing the reference to that array?

答案1

得分: 0

因为您在本地修改对 arr1 的引用(无法修改调用者的引用)。将

arr1 = arr2;

改为

System.arraycopy(arr2, 0, arr1, 0, arr2.length);
英文:

Because you are modifying the reference to arr1 locally (you can't modify the caller's reference). Change

arr1 = arr2;

to

System.arraycopy(arr2, 0, arr1, 0, arr2.length);

huangapple
  • 本文由 发表于 2020年9月28日 03:54:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64092704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定