Java 复制矩阵
我必须复制矩阵并更改新矩阵,但不想更改初始矩阵。我用arraylist of arraylist来表示它们。这是我的密码Java 复制矩阵,java,arraylist,Java,Arraylist,我必须复制矩阵并更改新矩阵,但不想更改初始矩阵。我用arraylist of arraylist来表示它们。这是我的密码 ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> row : matrix) { for(Integer index :
ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
for(Integer index : row) {
tempMatrix.get(row).add(index);
}
}
ArrayList tempMatrix=新建ArrayList();
对于(ArrayList行:矩阵){
for(整数索引:行){
tempMatrix.get(行)、add(索引);
}
}
编译器说,为此目的使用get方法是非法的。我还可以做些什么来复制?您只需复制整行即可,省去了很多麻烦:
ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
tempMatrix.add(new ArrayList<Integer>(row));
}
ArrayList tempMatrix=新建ArrayList();
对于(ArrayList行:矩阵){
添加(新数组列表(行));
}
您只需复制整行即可,省去了很多麻烦:
ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
tempMatrix.add(new ArrayList<Integer>(row));
}
ArrayList tempMatrix=新建ArrayList();
对于(ArrayList行:矩阵){
添加(新数组列表(行));
}
试试:
for(ArrayList行:矩阵){
ArrayList行列表=新建ArrayList();
for(整数索引:行){
添加(索引);
}
tempMatrix.add(行列表);
}
试试:
for(ArrayList行:矩阵){
ArrayList行列表=新建ArrayList();
for(整数索引:行){
添加(索引);
}
tempMatrix.add(行列表);
}
您需要克隆arraylist:
ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
tempMatrix.add(row.clone());
}
ArrayList tempMatrix=新建ArrayList();
对于(ArrayList行:矩阵){
tempMatrix.add(row.clone());
}
如果使用new
Arraylist
,则确实会有一个新的Arraylist
,但它包含的元素将引用作为构造函数参数传入的数组中包含的元素。您需要克隆Arraylist:
ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
tempMatrix.add(row.clone());
}
ArrayList tempMatrix=新建ArrayList();
对于(ArrayList行:矩阵){
tempMatrix.add(row.clone());
}
如果使用new
Arraylist
,则实际上会有一个新的Arraylist
,但它包含的元素将引用作为构造函数参数传入的数组中包含的元素。请参见错误。。。。get用于获取索引的元素。。。您传递的是对象,而不是应该为int的索引。请检查ArrayList的javadoc查看错误。。。。get用于获取索引的元素。。。您传递的是对象,而不是应该是int的索引。请检查ArrayList的javadoc非常感谢!我试着这样做,但我的初始矩阵仍然在变化。难道没有任何方法可以通过值而不是引用进行复制吗?那会很奇怪,因为新建数组列表(行)
应该创建一个全新的数组列表,复制行的内容。你确定矩阵没有在其他地方被修改吗?非常感谢!我试着这样做,但我的初始矩阵仍然在变化。难道没有任何方法可以通过值而不是引用进行复制吗?那会很奇怪,因为新建数组列表(行)
应该创建一个全新的数组列表,复制行的内容。你确定矩阵没有在其他地方被修改吗?