java - No parameter pass by reference in Java?
问题描述
I'm stuck on a simple array problem and need some guidance from my fellow programmers.
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
double[] array2, array3;
array2 = getArray();
array3 = getArray();
array2[0] = 99;
System.out.println(Arrays.toString(array2));
System.out.println(Arrays.toString(array3));
}
public static double[] getArray() {
double[] array1 = {1,2,3};
return array1;
}
}
Here is the output:
[99.0, 2.0, 3.0]
[1.0, 2.0, 3.0]
It is my understanding that java objects are passed by reference. However, when I change the first value of array2, why does the values for array3 stay the same? Shouldn't array3 also change its first value since both array2 and array3 reference the same array, in this case, array1?
解决方案
array2
and array3
don't reference the same array, since you initialize them by calling getArray()
, and each call to getArray()
returns a new array instance.
In order for them to reference the same array, you'll have to either change your code to:
array2 = getArray();
array3 = array2;
or change getArray()
to always return the same array:
private static double[] array1 = {1,2,3};
public static double[] getArray()
{
return array1;
}
推荐阅读
- single-sign-on - 使用 JHipster UAA 的 SSO(单点登录)
- ckeditor - ckeditor 3.6 - 超链接功能问题
- php - Show certain countries on WooCommerce checkout for particular products in cart
- flutter - 我无法根据越南的经纬度颤振地理定位器获取邮政编码
- optimization - 具有非凸约束的复值最小二乘优化
- json - 使用 jq 在 bash 中构建 json
- python - 使用 LXML 解析获取 XML 文件的节点属性
- c# - 将应用程序提升到受限用户的管理权限
- flutter - CupertinoTabView 在热重载时重置
- java - 堆直方图中的 OutOfMemory 实例