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 <T> List<T> deepCopy(List<T> 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<T> dest = (List<T>) 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<Person> srcList=new ArrayList<Person>();
srcList.add(new Person(10,"张三"));
srcList.add(new Person(11,"李四"));
List<Person> 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的方式)中有,这里就不重复了