简体   繁体   English

复制矩阵

[英]Copying matrices

I have to copy the matrix and change the new matrix, but don't want to change the initial one. 我必须复制矩阵并更改新矩阵,但是不想更改初始矩阵。 I represent them by arraylist of arraylists. 我用arraylists的arraylist表示它们。 Here is my code 这是我的代码

ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
        for(ArrayList<Integer> row : matrix) {
            for(Integer index : row) {
                tempMatrix.get(row).add(index);
            }
        }

Compiler says that it's illegal to use get method for this purpose. 编译器说,为此目的使用get方法是非法的。 What else can I do to copy? 我还能做什么复制?

You can just copy the whole row, saving yourself a lot of trouble: 您可以复制整行,从而省去了很多麻烦:

ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> row : matrix) {
    tempMatrix.add(new ArrayList<Integer>(row));
}

Try: 尝试:

  for(ArrayList<Integer> row : matrix) {
        ArrayList<Integer> rowList = new ArrayList<Integer>();
        for(Integer index : row) {
            rowList.add(index);
        }
        tempMatrix.add(rowList);
    }

You need to clone the arraylist: 您需要克隆arraylist:

    ArrayList<ArrayList<Integer>> tempMatrix = new ArrayList<ArrayList<Integer>>();
    for(ArrayList<Integer> row : matrix) {
         tempMatrix.add(row.clone());
    }

If you use new Arraylist then you will have a new arraylist indeed but the elements it contains will be a reference to the elements contained in the array that is passed into as constructor argument. 如果使用新的Arraylist则确实会有一个新的arraylist但是其中包含的元素将引用作为传递给构造函数参数的数组中包含的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM