java array pass by reference does not work?
Posted
by stdnoit
on Stack Overflow
See other posts from Stack Overflow
or by stdnoit
Published on 2010-05-14T04:45:17Z
Indexed on
2010/05/14
4:54 UTC
Read the original article
Hit count: 207
java
guys i thought almost all language 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 work . 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. that is why a 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;
}
}
© Stack Overflow or respective owner