我想使用Java中的循环创建动态矩阵2d。我的代码是
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);
}
}
第一个问题,如何用循环创建动态矩阵2D?我想要类似[[0,1,2],[0,1,2],[0,1,2]]的输出,并将矩阵值保存在变量组中。
第二个问题,保存在变量组中后,如果要删除变量中的列表(3号)怎么办?因此,输出为[[0,1,2],[0,1,2]]。
谢谢。
最佳答案
对于其余的代码,通过更改创建一个列表List<List<Integer>>
single.add(i);
至
single = new ArrayList<>(); // reset every iteration
for (int j=0; j < 3; j++) {
single.add(j); // add 0,1,2
}
如果我要删除变量中的列表(3号)怎么办?
group.remove(2); //removes the element at index 2