in the Android Java world, is there a straighforward (ideally one-call) way to convert an array of int
to an ArrayList<Integer>
and back? Calling toArray()
on the ArrayList returns an array of Integer
- not quite what I want.
I can easily do that by hand with a loop (already did, in fact). I'm wondering if the library/language supports the same.
EDIT: thanks all, I already wrote my own boxer and unboxer. I'm just surprised the language/RTL designers didn't think of it themselves, especially with primitive types being by design ineligible for collections.
Boxing and unboxing (without special libraries):
// Necessary Imports:
import java.util.*;
import java.util.stream.*;
// Integers:
int[] primitives = {1, 2, 3};
Integer[] boxed = Arrays.stream(primitives).boxed().toArray(Integer[]::new);
int[] unboxed = Arrays.stream(boxed).mapToInt(Integer::intValue).toArray();
// Doubles:
double[] primitives = {1.0, 2.0, 3.0};
Double[] boxed = Arrays.stream(primitives).boxed().toArray(Double[]::new);
double[] unboxed = Arrays.stream(boxed).mapToDouble(Double::doubleValue).toArray();
Note that this requires Java 8 (Stream Documentation).
For anyone unaware of what the ::
means, it's used to make a Method Reference.