Sunday 4 December 2016

java array pass by reference does not work?

I thought almost all languages, including java, pass array into function as reference (modifiable).



But somehow it does not work here, and the testArray is still 1,2,3 with size of 3.



Strange enough, when if I change result[i] = 2 to a[1] =2 it works. It did pass by reference.



What is wrong with this code?



At the end, I had a = result; (which update the a). Did result get removed from stack. Is that why I still get to the original a?




I am confused.



Thanks!



class Test
{
public static void main(String[] args)
{

int[] testArray = {1,2,3};

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

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...