在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
)來實現深拷貝。