Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2d ArrayList placement

Tags:

java

arraylist

I want to use a ArrayList instead of an array on the following code:

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

That's how the ArrayList should look like I guess:

ArrayList<ArrayList<String>>ar1 = new ArrayList<ArrayList<String>>();

But it's so confusing since I can't use the get method .. I don't know how to do that.

like image 1000
Imri Persiado Avatar asked Dec 11 '12 01:12

Imri Persiado


1 Answers

Try this way

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));

Output:

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)
like image 199
Pshemo Avatar answered Sep 26 '22 23:09

Pshemo