The copy constructor creates dependent copy

前端 未结 5 1137
盖世英雄少女心
盖世英雄少女心 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:25

    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(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.

提交回复
热议问题