副本构造函数创建依赖副本 [英] The copy constructor creates dependent copy

查看:63
本文介绍了副本构造函数创建依赖副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了副本构造器,如此处所述。但是问题仍然是,当我更新 route_copy 时,相同的更新将应用于 route 。因此,我不明白我的代码有什么问题?

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. So, I don't understand what is wrong in my 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); // !!! now 'route' does not contain an  element 's'
}


推荐答案

在复制构造函数中,您只是在进行浅表复制,而需要进行深层复制:

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

此处,您仍在复制的引用list ,它仍然指向相同的 ArrayList 。您也应该对其进行修改以创建列表的副本。可能还需要像下面这样在arraylist中创建元素的副本:

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

检查此帖子-浅拷贝与深拷贝。

这篇关于副本构造函数创建依赖副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆