nimafl nimafl - 1 year ago 129
Java Question

Convert ArrayList<double[][]> to double[][]

I have an array list where each element of it is a

list. Now if the array list contains n members, I want my output to be a list of size
. Based on this post I tried the following:

ArrayList<double[][]> testArray = new ArrayList<double[][]>();
double [][] testList = new double[testArray.size()][];
for(double [][] temp : testArray){
// temp is a list?

I also tried the following:

double [][] test = new double[testArray.size()][3];
test = testArray.toArray(test);

None of them are working for me. Any help would be much appreciated. Thanks.

Answer Source

If all arrays in list have 1st dimension size equal to one then you can try:

ArrayList<double[][]> testArray = new ArrayList<double[][]>();
int testArraySize = testArray.size();
double [][] testList = new double[testArraySize][];

for (int i = 0; i < testArraySize; i++) {
    testList[i] = testArray.get(i)[0];

I think it's pretty straightforward so I'll comment only on that:


This takes i-th element from list, which is a two dimensional array and then that operator in invoked [0] which accesses second dimension which is what we want to copy to target array. It all works under requirement that first dimensions of arrays in list have size equal to one.

// temp is a list?

No, it is a two dimensional array - it's a list element.

Your second snippet have no chance of working in that case since toArray creates an array in which every array element is an element from list so three dimensional array would be created. But still if you would use that method then to you would have to provide one dimensional array as a parameter to that method (not two dimensional) because toArray takes and returns one dimensional array. In your case that would be one dimensional array in which every element is a two dimensional array which results in having three dimensional array which is not what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download