java - Java中的深拷贝对象ArrayList
问题描述
要复制的 Java 对象:
public class InfoDtcEx implements Serializable {
private static final long serialVersionUID = 1L;
private String infoCall="";
private String infoNotCall="";
private String infoTarget="";
private String infoTotal="";
private String infoValue="";
private ArrayList<String> valueList;
public InfoDtcEx(String infoCall, String infoNotCall,
String infoTarget, String infoTotal, String infoValue) {
this.infoCall = infoCall;
this.infoNotCall = infoNotCall;
this.infoTarget = infoTarget;
this.infoTotal = infoTotal;
this.infoValue = infoValue;
this.infoValueBefore = this.infoValue;
}
public InfoDtcEx(InfoDtc infoDtc) {
this.infoCall = infoDtc.getinfoDtcCall();
this.infoNotCall = infoDtc.getinfoDtcNotCall();
this.infoTotal = infoDtc.getinfoDtcTotal();
this.infoValue = infoDtc.getinfoDtcValue();
this.infoValueBefore = this.infoValue;
}
//getters and setters
}
我尝试使用以下方法进行深度复制,如如何将元素从 ArrayList 复制到另一个不通过引用?:
private ArrayList<InfoDtcEx> copyInfoList(ArrayList<InfoDtcEx> infoListExChanged) {
infoListExChanged.clear();
for (int i = 0; i < infoListEx.size(); i++) {
String infoCall = infoListEx.get(i).getinfoCall();
if(infoCall != "Yes") {
infoListExChanged.add(infoListEx.get(i));
}
}
return infoListExChanged;
}
但是,这也改变了实际的列表 infoListEx。
解决方案
您没有按照链接到的帖子中的建议执行深层复制。
该帖子在接受的答案中有以下行:
copia.add(new Articulo_Venta(av.get(i)));
注意new Articulo_Venta
. 您的代码没有调用new
.
因此,请尝试更改要添加到列表的行以创建新对象,因此:
infoListExChanged.add(new InfoDtcEx(infoListEx.get(i)));
推荐阅读
- amazon-web-services - AWS 配额的真正最大值是多少?
- django - 如何在多个服务中复制 django 身份验证
- regex - 使用 regex101 获取第一个匹配字符串上方的所有行
- arrays - 裁剪具有预定位置的图像(矩阵或数组)
- amazon-s3 - 如何使用雪花删除 AWS s3 分区并将新文件更新到每个分区中
- google-sheets - 谷歌表格:带有多个问题的表单编辑修复了重复的答案
- powerbi-custom-visuals - 使用 Python 的 PowerBI 视觉效果
- html - 两个弹性盒的高度相同
- python - 使用 Keras 的分割模型时的图像分割输入形状
- c# - 将 JsonConverters 添加到 Azure 函数