How do I convert from this:
ArrayList<int[]>
-to-
int[]
?
Example
private ArrayList<int[]> example = new ArrayList<int[]>();
to
private int[] example;
e.g. ArrayList({1,2,3},{2,3,4}) to {1,2,3,2,3,4}
How do I convert from this:
ArrayList<int[]>
-to-
int[]
?
Example
private ArrayList<int[]> example = new ArrayList<int[]>();
to
private int[] example;
e.g. ArrayList({1,2,3},{2,3,4}) to {1,2,3,2,3,4}
The (slightly) tricky part of this problem is that you have to work out how big the output array needs to be before you start. So the solution is:
I'm not going to code this for you. You should be capable of coding it yourself. If not, you need to get capable ... by trying to do it yourself.
If the input and output types were different, there could have been a neater solution using a 3rd party library. But the fact that you are using int[]
makes it unlikely that you will find an existing library to help you.
quick cookbook on this : count the number of elements from each array, create an array to keep all the elements, copy the elements :)
import java.util.ArrayList;
// comentarios em pt-br
public class SeuQueVcConsegue {
public static void main(String[] args) {
ArrayList<int[]> meusNumerosDaSorte = new ArrayList<int[]>();
meusNumerosDaSorte.add(new int[]{1,2,3});
meusNumerosDaSorte.add(new int[]{4,5,6});
// conta os elementos
int contaTodosOsElementos = 0;
for( int[] foo : meusNumerosDaSorte){
contaTodosOsElementos += foo.length;
}
// transfere os elementos
int[] destinoFinal = new int[contaTodosOsElementos];
int ponteiro = 0;
for( int[] foo : meusNumerosDaSorte){
for( int n : foo){
destinoFinal[ponteiro] = n;
ponteiro ++;
}
}
// confere se esta correto :)
for(int n : destinoFinal){
System.out.println(n);
}
}
}