Java ArrayList of Arrays?

Rumpleteaser picture Rumpleteaser · Sep 4, 2010 · Viewed 127.8k times · Source

I want to create a mutli dimensional array without a fixed size.

I need to be able to add items of String[2] to it.

I have tried looking at:

private ArrayList<String[]> action = new ArrayList<String[2]>();

but that doesn't work. does anyone have any other ideas?

Answer

P&#233;ter T&#246;r&#246;k picture Péter Török · Sep 4, 2010

Should be

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...

You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you.

A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant.