在Java中,要实现数组的深拷贝,可以使用以下几种方法:
public static int[] deepCopy(int[] original) {
if (original == null) {
return null;
}
int[] copy = new int[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
return copy;
}
System.arraycopy()
方法:public static int[] deepCopy(int[] original) {
if (original == null) {
return null;
}
int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
return copy;
}
Arrays.copyOf()
方法:import java.util.Arrays;
public static int[] deepCopy(int[] original) {
if (original == null) {
return null;
}
return Arrays.copyOf(original, original.length);
}
Cloneable
接口并重写clone()
方法:public class MyClass implements Cloneable {
private int[] data;
public MyClass(int[] data) {
this.data = data;
}
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static MyClass deepCopy(MyClass original) throws CloneNotSupportedException {
if (original == null) {
return null;
}
MyClass copy = (MyClass) original.clone();
copy.setData(deepCopy(original.getData())); // 递归复制数组
return copy;
}
请注意,对于对象数组,深拷贝可能会导致循环引用问题。在这种情况下,可以考虑使用其他序列化方法(如ObjectInputStream
和ObjectOutputStream
)来实现深拷贝。