使用构造函数复制对象,Java
假设我想制作一个对象的深层副本,但使用它的构造函数。所以我有:
public class PositionList {
private Position[] data = new Position[0];
private int size = 0;
public PositionList(PositionList other, boolean deepCopy) {
if (deepCopy==true){
size=other.getSize();
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
}
else {
data=other.data;
size = other.size;
所以说我有这个被称为:
PositionList list = new PositionList();
PositionList acopy = new PositionList(list, true);
然而,我正在做的事情是不正确的,我不确定为什么..
So lets say I want to make a deep copy of an object, but using its contsructor. So I have:
public class PositionList {
private Position[] data = new Position[0];
private int size = 0;
public PositionList(PositionList other, boolean deepCopy) {
if (deepCopy==true){
size=other.getSize();
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
}
else {
data=other.data;
size = other.size;
And so say I have this being called:
PositionList list = new PositionList();
PositionList acopy = new PositionList(list, true);
What I am doing, however, is incorrect, and Im not sure why..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于您的深度复制逻辑:
您正在设置
size
字段(这与data
数组是多余的),但没有将新数组分配给data
字段,这可能是“深层”副本的全部要点。您应该将data
初始化为对方的size
(或other.data.length
):(并去掉
size
全部在一起)The problem lies in your deep copy logic:
You are setting the
size
field (which is redundant with thedata
array) but are not assigning a new array to thedata
field, which is presumably the whole point of your "deep" copy. You should initializedata
to the other'ssize
(orother.data.length
):(And get rid of
size
all together)