Search code examples
javaarraysarraylisttoarray

Making an Array out of an ArrayList containing Arraylists


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.


Solution

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