(Un) boxing primitive arrays in Java

in the Android Java world, is there a way to hide (ideally a single call) to convert an int array to an ArrayList<Integer> and vice versa? Calling toArray() in an ArrayList returns an Integer array - not quite what I want.

I can easily do this manually using a loop (already in fact). I am wondering if the library / language supports the same thing.

EDIT: thanks, I already wrote my own boxer and unboxer. I am simply surprised that the developers of the / RTL language did not think about it themselves, especially with primitive types that are not suitable for collections by design.

+6
source share
5 answers

Using Guava ( Ints.asList (int ...) and Ints.toArray (Collection <Integer>) ):

 int[] intArray = ... List<Integer> intArrayAsList = Ints.asList(intArray); int[] intArray2 = Ints.toArray(intArrayAsList); 

Note that like Arrays.asList , Ints.asList returns a list that is a representation of this array. You cannot add or remove from it, but you can set value at a specific index. You can also copy it to a new ArrayList if you want:

 List<Integer> arrayList = Lists.newArrayList(Ints.asList(intArray)); 

Guva has the same methods for all primitive types.

+9
source

If you create a utility method that will convert a single call. Perhaps in your case this will be better than adding an entire library (from which you can simply use one function), although this should be too much of a burden for your application.

Here's the source code for the h3xStream response (glad that it uses the Apache license);)

+3
source

Apache's Common.Lang has a Utility class that does this: ArrayUtils

+1
source

I managed to find a solution in Java 8:

 import java.util.Arrays; ... double[] columnsValue = {...}; Double[] values = Arrays.stream(columnsValue).boxed().toArray(Double[]::new); 

I can’t explain what Double[]::new means, because I didn’t know this feature of Java 8 before (actually IntelliJ IDEA wrote it for me), but it looks like it does new Double(double) on each element array.

Pay attention . I tested this only on the desktop, I don't know if it works on Android.

+1
source

Boxing and unpacking (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(); 

Please note that this requires Java 8 ( Stream Documentation ).

For those who do not know what :: means, he used the Method Link .

0
source

Source: https://habr.com/ru/post/888587/


All Articles