我实现了此处描述的副本构造函数。但是问题仍然是,当我更新时route_copy,会将相同的更新应用于route。所以,我不明白我的代码有什么问题?
route_copy
route
public class Route implements Comparable<Route> { private List<Site> sites; public Route() { sites = new ArrayList<Site>(); } public Route(List<Site> sites) { this.sites = sites; } /** * Copy constructor */ public Route(Route r) { this(r.sites); } public void deleteSite(Site s) { this.sites.remove(s); } } public processData(Route route) { Route route_copy = new Route(route); Site s = selectSite(route_copy); route_copy.deleteSite(s); // !!! now 'route' does not contain an element 's' }
在复制构造函数中,您只是在进行浅表复制,而您需要进行深表复制:
public Route(Route r) { this(r.sites); }
在这里,您仍在复制的引用,该引用list仍指向same ArrayList。您也应该对其进行修改以创建列表的副本。可能还需要像下面这样在arraylist中创建元素的副本:
list
ArrayList
public Route(Route r) { List<Site> newSites = new ArrayList<Site>(); for (Site obj: r.sites) { // Add copy of obj to the newSites // So you need yet another copy constructor in 'Site' class. } this.sites = newSites; }