副本构造函数创建依赖副本

编程入门 行业动态 更新时间:2024-10-28 12:20:14
本文介绍了副本构造函数创建依赖副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我实现了副本构造器,如此处所述。但是问题仍然是,当我更新 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; }

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

更多推荐

副本构造函数创建依赖副本

本文发布于:2023-10-25 03:07:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副本   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!