Modify an array passed as a method-parameter

后端 未结 4 1722
天涯浪人
天涯浪人 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:44

    As you correctly note, you cannot assign to the array reference passed as a parameter. (Or more precisely, the assignment won't have any effect in the caller.)

    This is about the best that you can do:

    public static void method(int[] n) {
        int[] temp = new int[]{2};
        for (int i = 0; i < temp.length; i++) {
            n[i] = temp[i];
        }
        // ... or the equivalent using System.arraycopy(...) or some such
    }
    

    Of course, this only works properly if the size of the input array is the same as the size of the array you are copying to it. (How you should deal with this will be application specific ...)


    For the record Java passes the array reference by value. It doesn't pass the array contents by value. And clone won't help to solve this problem. (At least, not with the method signature as declared.)

提交回复
热议问题