首页 > 解决方案 > 使对象的ArrayList在调用其他函数时复制不引用的值

问题描述

我想调用另一个函数,我不想更改我的数组列表。但是当我每次我的arraylist更改时调用该函数时。这是我的代码片段:

private ArrayList<LeftPanelObject> addAllNestingGroup(LinkedHashMap<String, ArrayList<LeftPanelObject>> rowGroupDataNesting) {
    ArrayList<LeftPanelObject> l1= new ArrayList<>();
    LeftPanelObject obj= new LeftPanelObject();
    for(String key:rowGroupDataNesting.keySet()){
        ArrayList<LeftPanelObject> rowData= new ArrayList<LeftPanelObject>();
        ArrayList<LeftPanelObject> rowDataB= new ArrayList<LeftPanelObject>();
        rowDataB=(ArrayList<LeftPanelObject>) rowGroupDataNesting.get(key).clone();
        rowData.addAll(rowDataB);
        obj=getNestingOfObj(obj,rowData,rowData.size(),rowData.size());
        }
    l1.add(obj);
    return l1;
}

//这里我正在改变结构 //leftpanelObject 是我的基本对象,包含它自己的 N 级嵌套参考

private LeftPanelObject getNestingOfObj(LeftPanelObject obj,
            final ArrayList<LeftPanelObject> rowData1,int size,int actualSize) {

    ArrayList<LeftPanelObject> rowData=new ArrayList<LeftPanelObject>(rowData1);
    int i=actualSize-size;
    if(i<actualSize){
        if(i==0){
            obj=rowData.get(i); 
            obj=getNestingOfObj(obj,(ArrayList<LeftPanelObject>) rowData.clone(),size-1,actualSize);
        }else{
            if(obj.getLevel()==null){
                obj.setGroupId(-1);
                obj.setRowId(-1);
                obj.setNestingLevel(-1);
                ArrayList<LeftPanelObject> temp=new ArrayList<>();
                temp.add(getNestingOfObj(rowData.get(i),(ArrayList<LeftPanelObject>) rowData.clone(),size-1,actualSize));
                obj.setLevel(temp);
            }else if(obj.getLevel().isEmpty()){
                obj.setGroupId(-1);
                obj.setRowId(-1);
                obj.setNestingLevel(-1);
                ArrayList<LeftPanelObject> temp=new ArrayList<>();
                temp.add(getNestingOfObj(rowData.get(i),(ArrayList<LeftPanelObject>) rowData.clone(),size-1,actualSize));
                obj.setLevel(temp);
            }else{
                for(int j=0;j<obj.getLevel().size();j++)
                getNestingOfObj(obj.getLevel().get(j),(ArrayList<LeftPanelObject>) rowData.clone(),size,actualSize);
            }
        }
    }else{
        return obj;
    }
    return obj;

}

标签: javaarraylistcollectionsclone

解决方案


You just need to provide your getNestingOfObj method a new ArrayList<LeftPanelObject> instance.

getNestingOfObj(
     obj, 
     new ArrayList<>(rowData),
     rowData.size(),
     rowData.size()
);

The ArrayList<T> class offer a constructor which accept a Collection<T>

public ArrayList(Collection<? extends E> c) { ... }

推荐阅读