使用构造函数Java复制对象 [英] Copying an object using a constructor, Java
本文介绍了使用构造函数Java复制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想说,我想做一个对象的深层副本,但使用它的contsructor。所以我有:
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;
所以说我有这个叫:
PositionList list = new PositionList();
PositionList acopy = new PositionList(list, true);
然而,我在做什么不正确,
What I am doing, however, is incorrect, and Im not sure why..
推荐答案
问题在于你的复制逻辑:
The problem lies in your deep copy logic:
size=other.getSize();
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
您正在设置 size
与数据
数组是多余的),但是没有为数据
字段指定一个新数组,这可能是整个点你的深副本。您应该将数据
初始化为其他人的 size
(或 other.data.length
):
You are setting the size
field (which is redundant with the data
array) but are not assigning a new array to the data
field, which is presumably the whole point of your "deep" copy. You should initialize data
to the other's size
(or other.data.length
):
data = new Position[other.data.length];
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
(除掉 size
)
这篇关于使用构造函数Java复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文