The copy constructor creates dependent copy

前端 未结 5 1138
盖世英雄少女心
盖世英雄少女心 2021-01-23 16:34

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

5条回答
  •  春和景丽
    2021-01-23 17:12

    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.

提交回复
热议问题