The copy constructor creates dependent copy

最后都变了- 提交于 2019-12-02 05:47:52
Rohit Jain

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

Check this post - Shallow Copy vs Deep Copy.

Your "copy constructor" is not making a copy of the input list. Try something like

public Route(List<Site> sites)
{
    this.sites = new ArrayList<Site>(sites);
}

for your second constructor.

Ofcourse it'll create dependent copy also called Shallow copy.

You need a Deep copy.

The problem is that both lists are still pointing to the same memory location, thus, any operation on one list eventually modifies the other.

You can try and use the copy constructor of the ArrayList:

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Like so:

     public Route(Route r) {
     this(new ArrayList<Site>(r.sites));
     }

Note however that doing any modifications to the Site objects within the list might have repurcussions on the other objects stored in the other list, depending on how complex your Site object is.

what you do with the copy constructor is just make the new Route use the list of the old Route and therefor any change to one of them immediately effect the other

what you need to do is make the copy constructor make a new list:

sites = new ArrayList<Site>(oldList);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!