2d ArrayList放置

Imr*_*ado 5 java arraylist

我想在以下代码中使用ArrayList而不是数组:

for(int k=0;k<SIZE;k++) //size is 9
    for(int j=0;j<SIZE;j++)
        ar1[k][j] = buttons[k][j].getText();
Run Code Online (Sandbox Code Playgroud)

这就是我猜测ArrayList的样子:

ArrayList<ArrayList<String>>ar1 = new ArrayList<ArrayList<String>>();
Run Code Online (Sandbox Code Playgroud)

但是由于我不能使用get方法,所以令人困惑.我不知道该怎么做.

Psh*_*emo 2

试试这个方法

List<List<String>>ar1 = new ArrayList<>();
//lets say we want to have array [2, 4]
//we will initialize it with nulls
for (int i=0; i<2; i++){
    ar1.add(new ArrayList<String>());
    for(int j=0; j<4; j++)
        ar1.get(i).add(null);
}
System.out.println("empty array="+ar1);

//lets edit contend of that collection
ar1.get(0).set(1, "position (0 , 1)");
ar1.get(1).set(3, "position (1 , 3)");
System.out.println("edited array="+ar1);

//to get element [0, 1] we can use: ar1.get(0).get(1)
System.out.println("element at [0,1]="+ar1.get(0).get(1));
Run Code Online (Sandbox Code Playgroud)

输出:

empty array=[[null, null, null, null], [null, null, null, null]]
edited array=[[null, position (0 , 1), null, null], [null, null, null, position (1 , 3)]]
element at [0,1]=position (0 , 1)
Run Code Online (Sandbox Code Playgroud)