java序列化深层复制_深层复制与浅层复制(通过序列化的方式实现)

深层复制与浅层复制(通过序列化的方式实现)

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的方式)中有,这里就不重复了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值