首先,我不得不说这不是deep copying vs shallow copying (clone)
Java 中的副本。但它与此有关。我已经阅读deep vs shallow copying
了 SO 中的其他帖子,在处理这个问题时,我发现我的理解存在一些问题。问题是:clone() and system.arraycopy()
在下面的示例中给出不同的数组。但他们不应该这样做?
我在下面的另一个示例对象中使用数组作为字段。我再次看到它们是数组字段的不同引用。代码被注释以便于理解。
import java.util.Arrays;
import java.util.*;
class Example {
public int foo;
public int[] bar;
public Example (int foo, int[] bar) {
this.foo = foo;
this.bar = bar;
}
public void setfoo(int foo){
this.foo=foo;
}
public int[] getbar(){
return bar;
}
}
public class ClonevsDeepCopy {
public static void main(String[] args){
//Example 1
StringBuffer[] arr = {new StringBuffer("abc"),new StringBuffer("def"),
new StringBuffer("ghi")};
StringBuffer[] arr2 = arr.clone();
StringBuffer[] arr3 = new StringBuffer[3];
System.arraycopy(arr, 0, arr3, 0, 2);
//check for identity
System.out.println(arr==arr2);
System.out.println(arr==arr3);
//End of example 1
//Example 2
/*this is equivalent of shallow copying which is clone()
* The normal interpretation is that a "shallow" copy of eg1
* would be a new Example object whose foo equals 1
* and whose bar field refers to the same array as in the original; e.g.
*/
Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = new Example(eg1.foo,eg1.bar);
System.out.println(eg1.bar==eg2.bar);
eg1.setfoo(4);
eg1.bar[0]=99;
/*This is equivalent of deep coying
The normal interpretation of a "deep" copy of eg1 would
be a new Example object whose foo equals
1 and whose bar field refers to a copy of the original array; e.g.
*/
Example eg3 = new Example(eg1.foo,Arrays.copyOfRange(eg1.bar, 0, 2));
System.out.println(eg3.bar==eg1.bar);
//cloning on array
Example eg4 = new Example(eg1.foo,eg1.bar.clone());
System.out.println(eg4.bar==eg1.bar);
//End of example 2
}
}