Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...