I have this simple varargs method that divides each item in a list:
import java.util.*; class A { static long f(long... xs) { Arrays.sort(xs); long y = 100000000; for (int i = xs.length - 1; i >= 0; i--) y /= xs[i]; return y; } static { System.out.println(f(5,2,6,3,9,3,13,4,5)); long[] xs = new long[]{5,2,6,3,9,3,13,4,5}; System.out.println(Arrays.toString(xs)); System.out.println(f(xs)); System.out.println(Arrays.toString(xs)); } }
I expect it to pass in a copy of the array, but apparently it is somehow modifying the array I enter, instead of its own local copy:
$ javac A.java && java A 79 [5, 2, 6, 3, 9, 3, 13, 4, 5] 79 [2, 3, 3, 4, 5, 5, 6, 9, 13]
So, I wrote this simple test program:
class B { static void f(Object... os) { System.out.println(os); } static { Object os = new Object[]{1,2,3}; System.out.println(os); f(os); } }
And it does what I expect, it clones an array of objects before passing it to f (hence the different object identifiers):
$ javac B.java && java B [Ljava.lang.Object;@1242719c [Ljava.lang.Object;@4830c221
So, how then can f in A change the caller's array instead of its own copy?