java - The copy constructor creates dependent copy -
i implemented copy constructor described here. still problem when update route_copy, same update applied route. so, don't understand wrong in code?
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); // !!! 'route' not contain element 's' }
in copy constructor, doing shallow copy, while need deep copy:
public route(route r) { this(r.sites); } here, still copying reference of list, still points same arraylist. should modify create copy of list too. possibly, need create copy of elements inside arraylist so:
public route(route r) { list<site> newsites = new arraylist<site>(); (site obj: r.sites) { // add copy of obj newsites // need yet copy constructor in 'site' class. } this.sites = newsites; } check post - shallow copy vs deep copy.
Comments
Post a Comment