简体   繁体   中英

Deep copy Object ArrayList in Java

Java object to copy:

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
    
    }

I tried Using below method to deep copy as suggested at 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;
    }

But, this is changing the actual list infoListEx as well.

You are not performing the deep copy as suggested in the post you linked to.

That post had the following line in the accepted answer:

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

Notice the construction of the new Articulo_Venta . Your code is not calling new .

So try changing your line where you are adding to the list to create a new object, so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM