在Java中数组是通过值传递还是通过引用传递?数组不是原语类型在Java中,但是它们也不是对象那么,它们是以价值还是参照的方式传递的呢?它是否取决于数组所包含的内容,例如引用或基本类型?
3 回答
慕森卡
TA贡献1806条经验 获得超8个赞
// assuming you allocated the listpublic void addItem(Integer[] list, int item) {
list[1] = item;}// assuming you allocated the listpublic void changeArray(Integer[] list) {
list = null;}
萧十郎
TA贡献1815条经验 获得超13个赞
Everything in Java are passed-by value.
通过该引用对数组内容的任何更改都将影响原始数组。 但是,将引用更改为指向新数组并不会更改原始方法中现有的引用。
参见下面的工作示例:-
public static void changeContent(int[] arr) {
// If we change the content of arr.
arr[0] = 10; // Will change the content of array in main()}public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15;}public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
changeContent(arr);
System.out.println(arr[0]); // Will print 10..
changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't reflect change here..}添加回答
举报
0/150
提交
取消
