java array pass by reference does not work?

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 78 answers

  • The array is passed by reference, but the reference is passed by value. That is, you can change the array that a refers to, but you cannot change which array a refers to.


    Java is pass by value. This is why your code does not work. A good practice would be to mark int[] a as final so this would result in a compilation error (see the corresponding Checkstyle rule).


    return parameter "a" from the function and assign to testArray in the main function. When you pass an object by reference, the reference is copied and given to the function. So the object is now referenced by 2 references. Any changes in the object through the 2nd reference will reflect in the first reference, because it is the same object referenced by both of them. But when you change the reference (not the object through reference), it is a different case. you have changed the 2nd reference to point to another object(int[] result). So any changes through the 2nd reference will change only the "result" object.

    class Test
    {
       public static void main(String[] args)
       {
    
          int[] testArray = {1,2,3};
          testArray = equalize(testArray, 6);
    
          System.out.println("test Array size :" + testArray.length);
          for(int i = 0; i < testArray.length; i++)
             System.out.println(testArray[i]);
       }
    
       public static int[] equalize(int[] a, int biggerSize)
       {
          if(a.length > biggerSize)
             throw new Error("Array size bigger than biggerSize");
    
          int[] result = new int[biggerSize];
         // System.arraycopy(a, 0, result, 0, a.length);
         // int array default value should be 0
          for(int i = 0; i < biggerSize; i++)
             result[i] = 2;
    
          a = result;
          return a;
       }
    }
    
    链接地址: http://www.djcxy.com/p/3504.html

    上一篇: 为什么修改ArrayList参数,但不是String参数?

    下一篇: java数组通过引用不起作用?