java面试的常见io操作 ~ 深拷贝

 

  java的clone方法实现的是浅拷贝,如果被拷贝的object里面有子object,子object有孙object。。。的话,这些object的内容就消失了。

除非你对每个子/孙的object的clone方法都重载。当然这东西太2b,人类都不这么玩的。

       最简单的实现方式是使用ByteArrayOutputStream和ByteArrayInputStream()来将一个object转换成byte流变换。先将它write到输出流,再重输入流read。实现它内容的拷贝。

 

package com.interview.scoop;

 

 

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.Stack;

 

public class DeepClone {

    public static void main(String[] args) {

        Stack<Integer> s = new Stack<Integer>();

        for(int i = 0; i < 3; i++) {

            s.push(i);

        }

        @SuppressWarnings("unchecked")

        Stack<Integer> b = (Stack<Integer>) DeepClone.copy(s);

        int size = b.size();

        for(int i = 0; i < size; i++) {

            System.out.println(b.pop());

        }

    }

    public static Object copy(Object oldObj) {

        Object o = null;

       //Used to carry the output

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {

             // Used to method output

            ObjectOutputStream oos = new ObjectOutputStream(bos);

            // Write object to the container

            oos.writeObject(oldObj);

            // flush is not necessities

            oos.flush();

            oos.close();

            // container, give the object to it, which will be translate to stream

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

           // tool

            ObjectInputStream ois = new ObjectInputStream(bis);

            try {

                // read target and get an object

                o = ois.readObject();

            } catch (ClassNotFoundException e) {

                e.printStackTrace();

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

                return o;

        }

    } 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值