-6

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}

Igor
  • 33,276
  • 14
  • 79
  • 112

2 Answers2

2

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:

  1. Loop over the list to sum the size of the arrays in the list
  2. Allocate the output array
  3. Use a nested loop to copy the integers to the output array.

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

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);
        }

    }
}
hamilton.lima
  • 1,902
  • 18
  • 29