I implemented the copy constructor as it is described here. But still the problem is that when I update route_copy
, then the same update is applied to route>
In your copy constructor, you are just doing a shallow copy, while you need to do a deep copy:
public Route(Route r) {
this(r.sites);
}
Here, you are still copying the reference of the list
, which still points to the same ArrayList
. You should modify it to create copy of list too. Possibly, you also need to create copy of the elements inside the arraylist like so:
public Route(Route r) {
List newSites = new ArrayList();
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;
}
Check this post - Shallow Copy vs Deep Copy.