继原型模式的续,本文分享的是浅拷贝和深拷贝
深入了解浅拷贝与深拷贝
在学习深拷贝和浅拷贝之前,咱们先来一个例子;
-
import java.util.ArrayList;
-
public class MyBaby implements Cloneable {
-
/**
-
* 私有变量
-
*/
-
private ArrayList<String> list = new ArrayList<>();
-
@Override
-
protected Object clone() throws CloneNotSupportedException {
-
MyBaby myBaby = null;
-
try {
-
myBaby = (MyBaby) super.clone();
-
} catch (CloneNotSupportedException ex) {
-
ex.printStackTrace();
-
}
-
return myBaby;
-
}
-
/**
-
* 给List设置
-
*
-
* @param value 值
-
*/
-
public void setValue(String value) {
-
this.list.add(value);
-
}
-
/**
-
* 获取list
-
*
-
* @return list
-
*/
-
public ArrayList<String> getValue() {
-
return this.list;
-
}
-
}
在MyBaby类中有一个私有变量list,类似为List,然后咱们使用setValue对其进行设值,使用getValue进行取值。接下来咱们来看看他是如何拷贝的。
-
public class TestMyBaby {
-
public static void main(String[] args) {
-
MyBaby baby = new MyBaby();
-
baby.setValue("Java后端技术栈");
-
try {
-
MyBaby myBabyClone = (MyBaby) baby.clone();
-
myBabyClone.setValue("咖啡");
-
-
System.out.println(baby.getValue());
-
} catch (CloneNotSupportedException e) {
-
e.printStackTrace();
-
}
-
}
-
}
猜想运行结果会是神马?
[Java后端技术栈, 咖啡]
怎么会这样呢?怎么会有“咖啡”呢?
是因为Java给我们做了一个偷懒性的拷贝动作,Object类原本就提供一个方法clone用来拷贝对象,因为其对象内部的数组、引用对象等都不拷贝,还是指向了原生对象的内部元素地址,这种拷贝就叫做浅拷贝。
浅拷贝
上面这个拷贝也太浅了吧,两个对象引用都boby、myBaby共享一个私有变量list,都可以对list进行改变,是一种非常不安全的方式。
再看一个例子;
-
public class Person implements Cloneable {
-
private int age;
-
private String name;
-
public int getAge() {
-
return age;
-
}
-
public void setAge(int age) {
-
this.age = age;
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
@Override
-
protected Object clone() throws CloneNotSupportedException {
-
Person person=null;
-
try{
-
person=(Person)super.clone();
-
}catch (CloneNotSupportedException ex){
-
ex.printStackTrace();
-
}
-
return person;
-
}
-
}
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:java对象---深/浅拷贝