How do you add to a 2D arraist

I have the following code. I know the star is correct, but I can not add to arraylist

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

then i have

action.add({4,8});  // error

Why can't I add {4,8}to the list?

+3
source share
2 answers

You need to write it down completely:

action.add(new int[]{4,8});

A simple {...}short-hand only works when initializing an array during declaration:

int[] a = {4,8};  // works

int[] b;
b = {4,8};  // error

See JLS §10.6 for more details .

+3
source

You can also do it as follows:

int[] b = new int[2];
b[0] = 4;
b[1] = 8;

Then:

action.add(b);
+1
source

All Articles