Java: arrays as reference types, in methods

人盡茶涼 提交于 2020-01-15 11:38:36

问题


I am moving from C++ to Java, and I have a problem understanding how, in Java, an array lasts outside the method in which it was created. Take a look at this simple code below:

public static int[] arrayMethod(){
    int[] tempArray = {1, 2, 3, 4};
    return tempArray;
}

public static void main(String[] args){
    int arr[] = arrayMethod();
    for(int i : arr){
        System.out.println(i);
    }
}

In C++, unless the array is dynamically allocated with the new operator, the array would not exist after the call, because it was created locally in the method. As I understand it, Java is always pass by value, and arrays are reference types, so my c++ logic would tell me that I am returning a reference to a locally created array. What am I missing?


回答1:


Perhaps this will help you understand.

In Java, this:

int[] tempArray = {1, 2, 3, 4};

means exactly the same thing as this:

int[] tempArray = new int[]{1, 2, 3, 4};

There is an implicit new in the first form.

In Java, all arrays are heap objects / references. And when an array is passed to a method, it is handled the same way that any reference is handled; i.e. the reference is passed by value. (And no, this is NOT "call by reference" or "pass by reference" as those terms are properly understood.)




回答2:


Since you are returning a reference to the array which you then assign to int arr[], the array still has something pointing to it. So the garbage collector doesn't cull it because it is still has a reference.

It was a local variable, but then you returned it to your main method and assigned to it a variable, so the array persists.




回答3:


The reference to the array is passed by value. So what you have are 2 references. You would be returned a reference to the array, by value. So as long as reference is pointing to the array you could alter(apply some manipulation) to the array.

Now if you had 2 references pointing to same array altering array through either reference will alter the same array. But if at some point you change the value of reference, (i.e change the array to which the reference points) then those two reference will point to different arrays.

Important point is that here a reference is returned by value. Not array is returned with it's pointer. In short you are right. I actually have little understanding of C++

It's like there are 2 remotes to a TV set. But if you change one remote to point to some other TV set , 1st remote can still access the old TV.




回答4:


In Java, objects are passed by reference and values are passed by value. Arrays are objects and they are passed by reference. With pass by reference, you get pointers effect.



来源:https://stackoverflow.com/questions/15183387/java-arrays-as-reference-types-in-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!