深度克隆
深度克隆的两种方式
(1)通过clone,并且克隆内部元素
- 克隆对象需要实现Cloneable接口
- 内部对象也要实现这个接口
- 克隆的时候要克隆内部对象
public class Person implements Cloneable {
public Holder holder = new Holder();
@Override
protected Object clone() throws CloneNotSupportedException {
Person p= (Person) super.clone();
Holder holder=(Holder) holder.clone();
p.holder= holder;
return p;
}
}
class Holder implements Cloneable{
public String key = null;
public Object value = null;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
(2)通过序列化克隆
- 实现序列化Serializable接口
- 内部对象也要实现Serializable接口
- 对所有对象序列化
public class Worker implements Serializable {
public Holder2 holder = new Holder2();
@Override
protected Object clone() throws CloneNotSupportedException {
try {
ByteArrayOutputStream bos
= new ByteArrayOutputStream();
ObjectOutputStream outputStream
= new ObjectOutputStream(bos);
outputStream.writeObject(this);
ByteArrayInputStream bis
= new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois
= new ObjectInputStream(bis);
return ois.readObject();
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
}
}
class Holder2 implements Serializable {
public String key = null;
public Object value = null;
}
to be continue