英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论