使用Java final关键字时出错,无法修改Final ArrayList的副本

时间:2018-08-08 09:58:44

标签: java list arraylist integer final

我收到无法修改只读列表的错误。但是我只修改B(只读列表的副本)-那么为什么它不起作用?

给出一个m * n个元素的矩阵(m行,n列),以螺旋顺序返回矩阵的所有元素。

错误:

fatal: cannot move directory over file

JAVA代码:

Exception in thread "main" java.lang.UnsupportedOperationException: Read
only list. Mutations not allowed!
at MyList.remove(Main.java:43)
at Solution.goLeft(Solution.java:55)
at Solution.spiralOrder(Solution.java:13)
at Main.main(Main.java:329)

链接-https://www.interviewbit.com/problems/spiral-order-matrix-i/

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
    ArrayList<Integer> spiralOrderList;
public ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> A) {
    spiralOrderList = new ArrayList<Integer>();
    List<ArrayList<Integer>> B = A;
    int currentRow=0;
    while(A.size()!=0){
        B=goRight(currentRow,B);
        currentRow++;
        B=goDown(currentRow,B);
        currentRow=B.size()-1;
        B=goLeft(currentRow,B);
        currentRow=B.size()-1;
        B=goUp(currentRow,B);    
        currentRow=0;
    }
    return spiralOrderList;
}
private  List<ArrayList<Integer>> goUp(int currentRow,List<ArrayList<Integer>> A){
    while(currentRow>=0){
        System.out.println(currentRow);
        spiralOrderList.add(A.get(currentRow).get(0));//print element at start
        A.get(currentRow).remove(0);//remove element
        currentRow--;
    }
    return A;
}
private List<ArrayList<Integer>> goDown(int currentRow,List<ArrayList<Integer>> A){
    while(currentRow<A.size()){
        int size = A.get(currentRow).size();//get Last Element Index 
        spiralOrderList.add(A.get(currentRow).get(size-1));
        System.out.println(A.get(currentRow).get(size-1));
        A.get(currentRow).remove(A.get(currentRow).get(size-1));//remove element
        currentRow++;
    }
    return A;
}
private List<ArrayList<Integer>> goRight(int currentRow,List<ArrayList<Integer>> A){
    for(int i=0;i<A.get(currentRow).size();i++)
    {
        System.out.println(A.get(currentRow).get(i));
        spiralOrderList.add(A.get(currentRow).get(i));
    }
    A.get(currentRow).clear();//remove row
    return A;
}
private List<ArrayList<Integer>> goLeft(int currentRow,List<ArrayList<Integer>> A){
    for(int i=A.get(currentRow).size()-1;i>=0;i--)
    {
        System.out.println(A.get(currentRow).get(i));
        spiralOrderList.add(A.get(currentRow).get(i));
    }
    System.out.println((A.size()-1)+"--");
    A.remove(A.get(currentRow));//remove row
    System.out.println((A.size()-1)+"//");
    return A;
}
}

1 个答案:

答案 0 :(得分:0)

ArrayList是一个对象。在Java中,当您将赋值运算符与对象一起使用时,它会进行全新复制,而是使两个引用变量都指向同一对象。
就您而言

List<ArrayList<Integer>> B = A;

B指向与A相同的最终ArrayList。

如果您想要A的副本,请使用。

List<ArrayList<Integer>> B = new ArrayList<>(A);   //pass List A as argument of constructor