Reputation: 105
I want to create dynamic matrix 2d using loop in java. My code is
class Mat {
public static void main (String[] args) throws java.lang.Exception {
List<List<Integer>> group = new ArrayList<>();
List<Integer> single = new ArrayList<>();
for (int i=0; i < 3; i++){
for (int j=0; j < 3; j++){
single.add(i);
}
group.add(single);
}
group.remove(3);
System.out.println(group);
}
}
First question, how to create dynamic matrix 2D with loop? I want an output like [[0,1,2], [0,1,2], [0,1,2]] and the matrix value saved in the variable group.
Second question, after being saved in the variable group, how about if I want to remove list (number 3) in the variable? So, output is [[0,1,2], [0,1,2]].
Thanks.
Upvotes: 0
Views: 266
Reputation: 31868
For the rest of your code creates a list List<List<Integer>>
by changing
single.add(i);
to
single = new ArrayList<>(); // reset every iteration
for (int j=0; j < 3; j++) {
single.add(j); // add 0,1,2
}
how if i want remove list (number 3) in the variable?
group.remove(2); //removes the element at index 2
Upvotes: 1