I have one question.
In Java I have an ArrayList containing an ArrayList with double-values. From this I want to make an double[][] array.
I know how to make it with an 1D- Array via the method 'toArray' but in this case I'm not sure how to do ist and always get an error message in my code.
My Aktuell Code is:
double[][] test = new double[Data.getArrayList().size()][Data.getArrayList().size()];
double[][] array = Data.getArrayList().toArray(test);
Where Data is my ArrayList of ArrayLists.
3 Answers 3
I would use a method like this (put it in an Utility class)
public static double[][] to2DArray(List<List<Double>> input) {
double[][] output = new double[input.size()][];
for (int i = 0; i < input.size(); i++) {
output[i] = new double[input.get(i).size()];
for (int j = 0; j < input.get(i).size(); j++) {
output[i][j] = input.get(i).get(j);
}
}
return output;
}
Comments
You have to
- iterate the outer ArrayList
- convert each entry to an array using toArray
- add these to an array of arrays, one by one
It's not beautiful, but there isn't really a better way to do it.
Comments
This is probably faster than iterating through every single element in the matrix:
private Double[][] to2DArray(ArrayList<ArrayList<Double>> data)
{
Double[][] result = new Double[data.size()][];
Double[] temp;
int mainIdx = 0;
for (List<Double> arrayOfDouble : data)
{
temp = new Double[arrayOfDouble.size()];
result[mainIdx++] = arrayOfDouble.toArray(temp);
}
return result;
}
8 Comments
Double[][], OP asked for a double[][]. No it's not faster, because you are also iterating over every single element in the matrix. You're just not doing it yourself, you let toArray() do it for you. You can see it iterating over every element in it's implementation.double[][] as output? But in Priniciple I'm would say Luis Ramos is right. Its always nicer to not use a loop in a loop and I think that the toArray-Order is better because I experianced, that build-in-methodes are alway faster than making it by yourself.double[][] would be to use my answer. This answer also contains a loop in a loop, because the implementation of toArray() contains a loop. If you compare the source of toArray() to my solution you will see that toArray() is neither faster nor slower in your case. But you are right, we shouldn't reinvent the wheel, if not necessary.
Data. If it were anArrayListthanData.getArrayList()would be a compiler error.Data.getArrayListI get out the data asArrayList<ArrayList<Double>>. But this shouldn't be the Problem.