在理解了深拷贝和浅拷贝后,我们来看看Java的深拷贝和浅拷贝实现。java.lang.t的clone()方法默认是返回一个前拷贝对象。因此如果要用clone()方法实现一个深拷贝,我们必须对每个对象的clone()方法进行特别实现。当对象层次复杂的时候,这样做不但困难而且浪费时间和容易出现错误,特别有时候你不但需要深拷贝同时你也对这个对象进行浅拷贝的时候,你会发现写这个clone()方法真不是一个好的解决方案。
dedecms.com
那么除了clone()方法,我们还可以怎么实现呢?答案是序列化,实现步骤和思路是把要拷贝的对象输出成bytearray,然后再利用tInputStream转换出新的对象。下面是代码
dedecms.com
public static t copy(t oldObj)
copyright dedecms
t obj = null; 本文来自织梦
try
// Write the t out to a byte array 本文来自织梦
ByteArrayOutputStream bos = new ByteArrayOutputStream();
织梦内容管理系统
tOutputStream out = new tOutputStream(bos); 织梦好,好织梦
out.writet(oldObj);
out.flush(); 织梦好,好织梦
out.close(); 织梦内容管理系统
// Retrieve an input stream from the byte array and read
内容来自dedecms
// a copy of the t back in.
织梦好,好织梦
ByteArrayInputStream bis =newByteArrayInputStream(bos.toByteArray()); 织梦好,好织梦
tInputStream in = new tInputStream(bis); copyright dedecms
obj = in.readt(); copyright dedecms
catch (IOException e)
织梦内容管理系统
e.printStackTrace(); dedecms.com
catch (ClassNotFoundException cnfe) copyright dedecms
cnfe.printStackTrace(); dedecms.com
return obj;









