[英]How to create dynamic matrix 2d in java?
我想使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.