深层复制与浅层复制(通过序列化的方式实现)
2014/7/27 21:49:08 mytdyhm123456 程序员俱乐部 我要评论(0)
摘要:packagecom.softstome.clone.arrayCopy.internet;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.util.ArrayList;importjava.util
package com.softstome.clone.arrayCopy.internet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.softstome.clone.Phone;
import com.softstome.clone.Student;
public class ListCopyDemo {
/*
* 使用序列化方法方法 ,实现集合的深层复制(推荐)
*
* 这也可以用来对象的克隆
* */
public static List deepCopy(List src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List dest = (List) in.readObject();
return dest;
}
public static Object deepCopyObj(Object src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
Object dest = in.readObject();
return dest;
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
// 集合的深层复制
/* List srcList=new ArrayList();
srcList.add(new Person(10,"张三"));
srcList.add(new Person(11,"李四"));
List descList=null;
descList=ListCopyDemo.deepCopy(srcList);
srcList.get(0).setName("张三1");
System.out.println(srcList);
System.out.println(descList);*/
/*
* 对象的深层复制
* */
/*Person src=new Person(12,"小杏");
Person desc=ListCopyDemo.deepCopyObj(src);
src.setAge(14);
System.out.println(src);
System.out.println(desc);*/
/*
* 对于有成员对象的对象的复制
* */
Student stu= new Student(2010032123, "周沈洁", new Phone("白色", "中兴"));
Student stu1=(Student)ListCopyDemo.deepCopyObj(stu);
stu.setStname("董洁");
stu.getPhone().setColor("黑色");
System.out.println(stu+" "+stu.getPhone());
System.out.println(stu1+" "+stu1.getPhone());
}
}
//说明 :Student类与Phone类在 :深层复制与浅层复制(通过clone的方式)中有,这里就不重复了