【问题标题】:Deep copy Object ArrayList in JavaJava中的深拷贝对象ArrayList
【发布时间】:2021-01-11 06:07:24
【问题描述】:

要复制的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
    
    }

我尝试按照How to copy elements from an ArrayList to another one NOT by reference? 的建议使用以下方法进行深度复制:

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


    【解决方案1】:

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

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

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

    注意new Articulo_Venta 的构造。你的代码没有调用new

    所以试着改变你要添加到列表中的行来创建一个新对象,所以:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      相关资源
      最近更新 更多