基本数据和引用数据
八中基本数据,存在于栈中,不存在深拷贝、浅拷贝
引用类型,通过Object c = a;这种引用方式产生的对象存在浅拷贝,即赋给的是a的地址,不论对a、c的修改都会互相影响,因为是一个对象。
深拷贝的三种方法:
1、通过new Instance,即new一个新对象,并逐一赋值属性;
2、通过重写Object类的clone方法(必须实现Cloneable接口)
public class Test implement Cloneable {
@Override
public Test clone(){
Test t = null;
try {
//clone方法可能因为找不到类而抛出CloneNotSupportedException错误
t = (Test) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return t;
}
}
3、通过序列化实现深复制
import java.io.*;
class Test implements Serializable {
//序列化方法,定义为copy
public Object copy()throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objo = new ObjectOutputStream(out);
objo.writeObject(this);
//将当前这个对象写到一个输出流当中,,因为这个对象的类实现了Serializable这个接口,所以在这个类中
//有一个引用,这个引用如果实现了序列化,那么这个也会写到这个输出流当中
ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream obji = new ObjectInputStream(input);
return obji.readObject();
//这个就是将流中的东西读出类,读到一个对象流当中,这样就可以返回这两个对象的东西,实现深克隆
}
}