Modify an array passed as a method-parameter

后端 未结 4 1721
天涯浪人
天涯浪人 2020-12-18 05:22

Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:

public static void main(String[] a         


        
4条回答
  •  悲哀的现实
    2020-12-18 05:51

    In your method

    public static void method(int[] n)
    

    n is another name for the array that way passed in. It points to the same place in memory as the original, which is an array of ints. If you change one of the values stored in that array, all names that point to it will see the change.

    However, in the actual method

    public static void method(int[] n) {
        int[] temp = new int[]{2};
        n = temp.clone();
    }
    

    You're creating a new array and then saying "the name 'n' now points at this, other array, not the one that was passed in". In effect, the name 'n' is no longer a name for the array that was passed in.

提交回复
热议问题