java - Varargs method modifies caller's array instead of its own copy? -
i have simple varargs method divides each item in list:
import java.util.*; class { static long f(long... xs) { arrays.sort(xs); long y = 100000000; (int = xs.length - 1; >= 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'd expect pass copy of array, apparently it's somehow modifying array pass in, instead of own local copy:
$ javac a.java && java 79 [5, 2, 6, 3, 9, 3, 13, 4, 5] 79 [2, 3, 3, 4, 5, 5, 6, 9, 13] so wrote 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 expect, clones object array before passing f (hence different object identifiers):
$ javac b.java && java b [ljava.lang.object;@1242719c [ljava.lang.object;@4830c221 so how f in a modifying caller's array instead of own copy?
it looks you've tricked here:
object os = new object[]{1,2,3}; system.out.println(os); f(os); since os typed object, gets interpreted first element of varargs array. gets passed method new object[] single element object[].
if following, print same instance:
object[] os = new object[]{1,2,3}; system.out.println(os); f(os); the f method need make defensive copy of array in order guarantee array passed in caller isn't modified. arshajii points out, varargs foremost array parameters, "bonus" behavior of creating new array when given argument list.
anyway can use arrays.copyof make copy, delegates (the less type-safe) system.arraycopy.
Comments
Post a Comment