首页 > 解决方案 > 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。

标签: java

解决方案


您没有按照链接到的帖子中的建议执行深层复制。

该帖子在接受的答案中有以下行:

copia.add(new Articulo_Venta(av.get(i)));

注意new Articulo_Venta. 您的代码没有调用new.

因此,请尝试更改要添加到列表的行以创建新对象,因此:

infoListExChanged.add(new InfoDtcEx(infoListEx.get(i)));

推荐阅读