Converting Array of Primitives to Array of Containers in Java
You have to loop through your array.
Updated after @seanizer answer :
Basically the toObject(byte[] array)
method will do the looping for you :
public static Byte[] toObject(byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BYTE_OBJECT_ARRAY;
}
final Byte[] result = new Byte[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Byte(array[i]);
}
return result;
}
And unless you will really use the commons lang lib, you should simply reuse this method and avoid a useless dependency (IMHO).
Apache Commons
Apache Commons / Lang has a class ArrayUtils that defines these methods.
- All methods called
toObject(...)
convert from primitive array to wrapper array - All called
toPrimitive(...)
convert from wrapper object array to primitive array
Example:
final int[] original = new int[] { 1, 2, 3 };
final Integer[] wrappers = ArrayUtils.toObject(original);
final int[] primitivesAgain = ArrayUtils.toPrimitive(wrappers);
assert Arrays.equals(original, primitivesAgain);
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:
List<Integer> intList = Ints.asList(1,2,3,4,5);
List<Long> longList = Longs.asList(1L,2L,3L,4L,5L);
// etc.
The nice think about these array-backed collections is that
- they are live views (i.e. updates to the array change the list and vice-versa)
- the wrapper objects are only created when needed (e.g. when iterating the List)
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:
int[] primitiveInts = {1, 2, 3};
Integer[] wrappedInts = Arrays.stream(primitiveInts)
.boxed()
.toArray(Integer[]::new);
int[] unwrappedInts = Arrays.stream(wrappedInts)
.mapToInt(Integer::intValue)
.toArray();
assertArrayEquals(primitiveInts, unwrappedInts);
double[] primitiveDoubles = {1.1d, 2.2d, 3.3d};
Double[] wrappedDoubles = Arrays.stream(primitiveDoubles)
.boxed()
.toArray(Double[]::new);
double[] unwrappedDoubles = Arrays.stream(wrappedDoubles)
.mapToDouble(Double::doubleValue)
.toArray();
assertArrayEquals(primitiveDoubles, unwrappedDoubles, 0.0001d);
Note that the Java 8 version works for int
, long
and double
, but not for byte
, as Arrays.stream() only has overloads for int[]
, long[]
, double[]
or a generic object T[]
.