Java copy ArrayList type INTEGER to array type INT

0

I need to manage dynamic arrays so I use an arraylist, considering that there is no int type arraylist use an integer type, but in the function I need to use the values of the arraylist, it only accepts INT type, so I need to copy them to a INT type array, I'm currently trying to do it like this:

ArrayList<Integer> NewptsX = new ArrayList<Integer>();
ArrayList<Integer> NewptsY = new ArrayList<Integer>();

int[] ptsX = NewptsX.toArray();
int[] ptsY = NewptsY.toArray();

Function that requires INT values:

h.drawPolygon(ptsX, ptsY, NLados);
h.fillPolygon(ptsX, ptsY, NLados);
    
asked by Oscar Acosta 09.11.2018 в 20:15
source

2 answers

0

Since the Integer and the int are different even if they accept the same data you should do them in the following way:

Using Java 8

With Java 8, int[] can be converted to 'Integer:

Integer[] primerInteger = Arrays.stream( ptsX ).boxed().toArray( Integer[]::new );
Integer[] segundoInteger = IntStream.of( ptsY ).boxed().toArray( Integer[]::new );

The other way would be using a click for

Integer[] nuevoArray = new Integer[ptsX.length];
int i = 0;
for (int valor : ptsX) {
    nuevoArray[i++] = Integer.valueOf(valor);
}
    
answered by 09.11.2018 в 20:42
0

First explain that Integer is an object (and therefore it can be null) and that int is a primitive data type. There is a generic way to do this, and it is using the existing property from java 1.5 which is called unboxing, by which the compiler does an automatic conversion from Integer to int. You just have to apply it for each element of the Integer array:

int i=0;
for (int valor : NewptsX) {
    ptsX[i++] = valor;
}

If we want to avoid possible NullPointerException (since Integer can be null), we have the following code:

int i=0;
for (Integer valor : NewptsX) {
    ptsX[i++] = (valor != null ? valor : 0);

}
    
answered by 10.11.2018 в 00:14