简体   繁体   中英

how do you add to a 2D arraylist

I have the following code. I know the star is correct but I can't add to the arraylist

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

then I have

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

Why cant I add {4,8} to the list?

You need to write it out in full:

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

The plain {...} short-hand only works when initializing the array at the time of declaration:

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

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

See JLS §10.6 for further details.

You can also do it as following:

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

Then:

action.add(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM