java - 使对象的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;
}
解决方案
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) { ... }
推荐阅读
- c# - WPF ItemsControl 和错误的 DataGrid
- html - 内容前的空白
- selected - 如何在选择类型奏鸣曲管理包上设置选定的选项
- azure-functions - 跨存储库的 Azure 持久函数
- java - 线程“主”java.lang.NoClassDefFoundError 中的异常:oracle/stellent/ridc/IdcClientManager
- python-3.x - Python 多行字符串的优雅解决方案?
- spring-cloud-contract - Spring Cloud 合约调试
- arrays - 如何使用循环变量创建二维 TCL 数组?
- java - 使用 Eclipse 和 Tomcat 时出现 404 错误
- jquery - 使用 jQuery 从一个 div 滚动到另一个(应该很容易)