[英]Java array cloning strange behavior
I'm trying to clone an instance of a custom class I made called CSP. 我正在尝试克隆我制作的自定义类CSP的实例。 I have one instance called csp and I want to make a clone of csp called cspclone. 我有一个名为csp的实例,我想复制一个名为cspclone的csp。 Here is what I'm using to do that: 这是我用来做的事情:
CSP cspclone = new CSP((csp.x).clone(), (csp.d).clone(), (csp.c).clone());
For some reason though when I pass cspclone to a method that modifies it csp gets modified also as if I forgot the .clone() functions but I didn't! 但是由于某种原因,当我将cspclone传递给修改它的方法时,csp也会被修改,就像我忘记了.clone()函数一样,但是我没有! Why is this happening?! 为什么会这样?
Override the clone
method in CSP
: 覆盖CSP
的clone
方法:
public class CSP {
private String aField;
private int[] array;
private int[][] twoDArr;
private List<ALContent> list; //here ALContent also needs to override clone properly
@Override
public Object clone() {
CSP clone = new CSP();
clone.aField = this.aField;
clone.array = new int[this.array.length];
System.arraycopy(this.array, 0, clone.array, 0, this.array.length);
clone.list = new ArrayList<ALContent>();
for(ALContent content : this.list) {
clone.list.add(content.clone()); //make sure you add the clone of the content
}
clone.twoDArr = new int[this.twoDArr.length][];
for(int i=0; i<this.twoDArr.length; i++) {
clone.twoDArr[i] = new int[this.twoDArr[i].length];
System.arraycopy(this.twoDArr[i], 0, clone.twoDArr[i], 0, this.twoDArr[i].length);
}
return clone;
}
}
Then you can do: 然后,您可以执行以下操作:
CSP csp = new CSP();
CSP cspClone = (CSP) csp.clone();
如果您的数组类型属性使用System.arraycopy
According to http://download.oracle.com/javase/1.3/docs/api/java/lang/Object.html#clone%28%29 根据http://download.oracle.com/javase/1.3/docs/api/java/lang/Object.html#clone%28%29
this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; 该方法创建该对象类的新实例,并使用该对象相应字段的内容完全初始化其所有字段,就像通过赋值一样; the contents of the fields are not themselves cloned. 字段的内容本身不会被克隆。 Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation. 因此,此方法执行此对象的“浅复制”,而不是“深复制”操作。
You might have to override the clone method and clone()
a reference type attribute within the object (ie, perform deep copy operation). 您可能必须重写 clone方法,并在对象clone()
一个引用类型的属性clone()
(即,执行深度复制操作)。
To solve your problem you need deep cloning. 要解决您的问题,您需要深度克隆。 The default clone method does a shallow copy. 默认克隆方法执行浅表复制。 See Object.clone() . 参见Object.clone() 。
Here are some approaches. 这里有一些方法。 All have advantages and drawbacks. 都有优点和缺点。
Here are several other stackoverflow discussions of cloning. 这是克隆的其他一些stackoverflow讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.