前几天编码遇到了深拷贝和浅拷贝,下面分享一下。
1.对于对象apple1直接赋值,其实只是存储对apple的引用,apple对象的修改会影响到apple1,apple1的修改会影响apple。
下面实现一下深拷贝,使apple和apple1的修改不会影响对方
public class Apple implements Cloneable{
private String name;
private String color;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return color;
}
@Override
public Object clone() throws CloneNotSupportedException {
Apple apple = (Apple) super.clone();
apple.name = this.name;
apple.color = this.color;
return apple;
}
}
public void Test(){
public static void main(String[] args) {
Apple apple = new Apple();
Apple apple1 = apple.clone();
}
}
2.对于容器的深拷贝的实现
public void Test{
public static void main(String[] args) {
Apple a = new Apple();
List list = new LinkedList();
list.add(a);
ListcopyList = deepCopy(list);
}
public static List deepCopy(List src) throws IOException, ClassNotFoundException{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in =new ObjectInputStream(byteIn);
List dest = (List)in.readObject();
return dest;
}
}