深拷贝与浅拷贝的应用场景. 无论是浅拷贝还是深拷贝,一般都用于操作Object 或 Array之类的复合类型。. 比如想对某个数组 或 对象的值进行修改,但是又要保留原来数组 或 对象的值不被修改,此时就可以用深拷贝来创建一个新的数组 或 对象,从而达到操作 (修改)新的数组 或 对象时,保留原来数组 或 对象。. 场景:从服务器fetch到数据之后我将其存放在store中,通过props传递给界面,然后我需要对这堆数据进行修改,那涉及到的修改就一定有保存和取消,所以我们需要将这堆数据拷贝到其它地方。
深拷贝:
package com.wyh.SE.clone;
public class DeepCloneExample implements Cloneable {
private int[] arr;
public DeepCloneExample() {
arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
@Override
protected DeepCloneExample clone() throws CloneNotSupportedException {
DeepCloneExample result = (DeepCloneExample) super.clone();
result.arr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result.arr[i] = arr[i];
}
return result;
}
}
浅拷贝:
package com.wyh.SE.clone.meet;
public class ShallowCloneExample implements Cloneable {
private int[] arr;
public ShallowCloneExample() {
arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
@Override
public ShallowCloneExample clone() throws CloneNotSupportedException {
return (ShallowCloneExample) super.clone();
}
}
测试:
package com.wyh.SE.clone;
import com.wyh.SE.clone.meet.ShallowCloneExample;
import java.util.HashSet;
public class TseTest {
public static void main(String[] args) throws CloneNotSupportedException {
DeepCloneExample e1 = new DeepCloneExample();
DeepCloneExample e2 = null;
ShallowCloneExample s1 = new ShallowCloneExample();
ShallowCloneExample s2 = null;
try {
//深拷贝
e2 = e1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
e1.set(2, 222);
System.out.println(e2.get(2)); // 2
//浅拷贝
s2=s1.clone();
s1.set(2,222);
System.out.println(s2.get(2));
}
}