简体   繁体   中英

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. 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. 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<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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