首页 > 解决方案 > 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?

标签: javapass-by-reference

解决方案


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;
}

推荐阅读