详解详解java中的深拷贝和浅拷贝(中的深拷贝和浅拷贝(clone()方法的重写、使用序列方法的重写、使用序列
化实现真正的深拷贝)化实现真正的深拷贝)
主要介绍了java中的深拷贝和浅拷贝(clone()方法的重写、使用序列化实现真正的深拷贝),文中通过示例代码介
绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1.序列化实现
public class CloneUtils {
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T object){
T cloneObj = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(object);
obs.close();
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(ios);
cloneObj = (T) ois.readObject();
}catch (Exception e){
e.printStackTrace();
}
return cloneObj;
}
}
2.主代码
public class TestString {
public static void main(String[] args) {
TestString test = new TestString();
System.out.println("-------浅拷贝---------");
test.qianCopyTest();
System.out.println();
System.out.println("--------使用clone深拷贝--------");
test.defaultCloneTest();
System.out.println();
System.out.println("--------使用序列化实现对象的拷贝--------");
test.streamClonrTest();
System.out.println("--------耗时对比--------");
System.out.println("耗时1 : "+ test.qianCopyCost());
System.out.println("耗时2 : "+ test.CloneCopyCost());
System.out.println("耗时3 : "+ test.StreamCopyCost());
}
/*浅拷贝*/
private void qianCopyTest() {
String s = "cd";
change(s);
System.out.println(s);
System.out.println("----------------");
String b = new String("cd");
change(b);
System.out.println(b);
System.out.println("----------------");
int me = 1;
change(me);
System.out.println(me);
System.out.println("----------------");
Person person = new Person("我", 13,new Email("我"));
change(person);
System.out.println(person.toString());
}
评论0