Java基础–浅拷贝与深拷贝
Java中可以使用Object类中的clone()方法实现拷贝,但使用 clone() 方法来拷贝一个对象即复杂又有风险,它会抛出异常,并且还需要类型转换。Effective Java 书上讲到,最好不要去使用 clone(),可以使用拷贝构造函数或者拷贝工厂来拷贝一个对象。
1、浅拷贝
拷贝对象和原始对象引用同一个对象
package com.java.basic;
public class ShallowCloneExample {
private int[] arr;
public ShallowCloneExample(){
arr = new int[10];
for(int i=0;i<10;i++){
arr[i] = i;
}
}
public int getValue(int index) {
return arr[index];
}
public void setValue(int index,int value) {
this.arr[index] = value;
}
private ShallowCloneExample shallowClone(ShallowCloneExample original){
return this;
}
public static void main(String[] args) {
ShallowCloneExample s1 = new ShallowCloneExample();
ShallowCloneExample s2 = s1.shallowClone(s1);
System.out.println(s1.getValue(2)); //2
System.out.println(s2.getValue(2)); //2
s1.setValue(2,20);
System.out.println(s1.getValue(2)); //20
System.out.println(s2.getValue(2)); //20
}
}
2、深拷贝
拷贝对象和原始对象引用不同的对象
package com.java.basic;
public class DeepCloneExample {
private int[] arr;
public DeepCloneExample(){
arr = new int[10];
for(int i=0;i<10;i++){
arr[i] = i;
}
}
private void setValue(int index,int value){
this.arr[index] = value;
}
private int getValue(int index){
return this.arr[index];
}
private DeepCloneExample(DeepCloneExample original){
arr = new int[10];
for(int i = 0;i<original.arr.length;i++){
arr[i] = original.arr[i];
}
}
public static void main(String[] args) {
DeepCloneExample d1 = new DeepCloneExample();
System.out.println(d1.getValue(2)); //2
DeepCloneExample d2 = new DeepCloneExample(d1);
System.out.println(d2.getValue(2)); //2
d1.setValue(2,20);
System.out.println(d1.getValue(2)); //20
System.out.println(d2.getValue(2)); //2
}
}