浅拷贝:使用一个已知实例对新创建实例的成员变量逐个赋值,这个方式被称为浅拷贝,实现Cloneable接口;
深拷贝:当一个类的拷贝构造方法,不仅要复制对象的所有非引用成员变量值,还要为引用类型的成员变量创建新的实例,并且初始化为形式参数实例值。这个方式称为深拷贝
public class User implements Serializable,Cloneable { public Integer id; PRivate String name; public User(Integer id,String name){ this.id = id; this.name = name; } //浅拷贝 public Object clone() throws CloneNotSupportedException { return super.clone(); } //深拷贝 public Object deepClone() throws IOException, ClassNotFoundException{ //定义一个输出流,将当前对象输出到流中 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); //定义一个输入流,将当前对象输入到流中,通过反序列化,从而获得对象 ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); }}新闻热点
疑难解答