Tom Carter
Tom Carter

Reputation: 155

Array to row on 2D List/ArrayList Java

I'm wanting to create a 2D array with a set amount columns (5) but an indefinite amount of rows. It was suggested to use a list with an arraylist like so List<List<String>> _upload = new ArrayList<List<String>>(); However this doesn't give me my 5 set columns I need.

My second problem is the way I'm feeding data into this 2D array. I'm given an array of information (5 long to fit a row) String[] _ToUpload = {"One", "Two","Three","Four","Five"};. How would go about implementing a method that created a new row and merged that array into the row of the 2D array.

New to Java so sorry if this seems a dumb question. Many thanks

Upvotes: 0

Views: 481

Answers (1)

Adeel Ahmad
Adeel Ahmad

Reputation: 305

Try this(I haven't tested it) :

// create an list named arrayList and add elements to the list
    String[][] array = new String[arrayList.size()][];
    for (int i = 0; i < arrayList.size(); i++) {
        ArrayList<String> row = arrayList.get(i);
        array[i] = row.toArray(new String[row.size()]);
    }

Upvotes: 1

Related Questions