I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I\'m not sure how to initialize such an array or store information.
I'm not sure how to initialize such an array or store information.
Like this for instance:
List> twoDim = new ArrayList>();
twoDim.add(Arrays.asList(0, 1, 0, 1, 0));
twoDim.add(Arrays.asList(0, 1, 1, 0, 1));
twoDim.add(Arrays.asList(0, 0, 0, 1, 0));
or like this if you prefer:
List> twoDim = new ArrayList>() {{
add(Arrays.asList(0, 1, 0, 1, 0));
add(Arrays.asList(0, 1, 1, 0, 1));
add(Arrays.asList(0, 0, 0, 1, 0));
}};
To insert a new row, you do
twoDim.add(new ArrayList());
and to append another element on a specific row you do
twoDim.get(row).add(someValue);
Here is a more complete example:
import java.util.*;
public class Test {
public static void main(String[] args) {
List> twoDim = new ArrayList>();
String[] inputLines = { "0 1 0 1 0", "0 1 1 0 1", "0 0 0 1 0" };
for (String line : inputLines) {
List row = new ArrayList();
Scanner s = new Scanner(line);
while (s.hasNextInt())
row.add(s.nextInt());
twoDim.add(row);
}
}
}