简体   繁体   中英

Casting primitive data type array to an OO array

Is there an elegant, clean way for converting primitive data type double array to OO Double array (eg double[] into Double[] )?

There are some nice solutions out there, eg

int[] intArray = { ... };
Integer[] what = Arrays.stream( intArray ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( intArray ).boxed().toArray( Integer[]::new );

(taken from here ), but this requires Java 8 . Is there a similar elegant, performant way for Java 7 and below?

If you want a one liner that compiles with Java 7, you can use ArrayUtils from Apache Commons. Eg

Integer[] what = ArrayUtils.toObject(intArray);

Works for any primitive type. That's probably more "elegant" and "clean" than the Java 8 code you posted. If you want to avoid libraries like Apache Commons, I am afraid you have to use a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM