Monday, 15 February 2010

arrays - Why autoboxing is not supporting in collection.toArray() in java -



arrays - Why autoboxing is not supporting in collection.toArray() in java -

is there no short cutting nicely?

that ugly 2 loops (one loop read pmlist , sec loop add together markuparray) alternative (instead of arrayutils).

arraylist<double> pmlist = new arraylist<double>(); pmlist.add(0.1); // adding through loop in real time. pmlist.add(0.1); pmlist.add(0.1); pmlist.add(0.1); double[] markuparray = new double[pmlist.size()]; arkuparray = pmlist.toarray(markuparray); // says method toarray(t[]) in type arraylist<double> not applicable arguments (double[])

simply utilize double[] array, instead of double[] works fine. if know size of list ahead of time, can skip list , insert straight array. might worth traverse input 2 times: 1 time retrieving size , 1 time insertion.

auto boxing works primitive types, not arrays of primitive types. double[] array no t[] array, since type parameter t must object. while double may autoboxed t (with t=double), double[] cannot autoboxed t[].

the reason why arrays not autoboxed operation costly: boxing array means creating new array , boxing each element. big arrays, has huge performance hit. don't want such costly operation done implicitly, hence no autoboxing arrays. in addition, boxing finish array yield new array. thus, when writing new array, changes not write through old array. see, there semantics problems array-boxing, not supported.

if must homecoming double[] array, must either write own function or utilize third-party library guava (see msandiford's answer). java collections framework has no methods (un)boxing of arrays.

java arrays collections

No comments:

Post a Comment