Is there an elegant way to turn an array of primitives into an array of the corresponding container objects — turn a byte[] into a Byte[], for example? Or am I stuck with looping through it and doing it manually?
Yeah, the for loop isn’t exactly difficult. Just kinda ugly.
Apache Commons
Apache Commons / Lang has a class ArrayUtils that defines these methods.
toObject(...)convert from primitive array to wrapper array
toPrimitive(...)convertfrom wrapper object array to
primitive array
Example:
Guava
But then I’d say that Arrays of wrapped primitives are not very useful, so you might want to have a look at Guava instead, which provides Lists of all numeric types, backed by primitive arrays:
The nice think about these array-backed collections is that
See: Guava Explained / Primitives
Java 8
On the other hand, with Java 8 lambdas / streams, you can make these conversions pretty simple without using external libraries:
Note that the Java 8 version works for
int,longanddouble, but not forbyte, as Arrays.stream() only has overloads forint[],long[],double[]or a generic objectT[].