Arrays.copyOf(T[ ] original, int newLength)
System.lang.arraycopy(Object src, int srcPos,Object dest, int destPos,int length);
都是浅复制
实际上, 前者是调用了后者:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
例子:
public class Test implements Cloneable{
private int x;
public void setX(int x)
{
this.x = x;
}
public int getX()
{
return x;
}
public Test(int x)
{
this.x = x;
}
public Object clone()
{
try {
Test t = (Test)super.clone(); //先执行浅克隆,确保类型正确和基本类型及非可变类类型字段内容正确
t.setX(x);
return t;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
public static void main(String[] args)
{
Test[] tests = new Test[3];
tests[0] = new Test(2);
tests[1] = new Test(2);
tests[2] = new Test(2);
Test[] ts = Arrays.copyOf(tests, 3); //[1]
tests[0].setX(10);
for(Test tt : tests)
System.out.println(tt.getX());
for(Test t : ts)
System.out.println(t.getX());
}
输出为:
10
2
2
10
2
2
若将[1]处代码修改为:
Test[] ts = new Test[3];
System.arraycopy(tests, 0, ts, 0, 3);
输出依然为:
10
2
2
10
2
2
若将[1]处代码修改为:
for(int i=0; i<tests.length; i++)
ts[i] = (Test)tests[i].clone();
输出则为:
10
2
2
2
2
2