亲宝软件园·资讯

展开

java 克隆对象 解析JAVA深度克隆与浅度克隆的区别介绍

人气:0
想了解解析JAVA深度克隆与浅度克隆的区别介绍的相关内容吗,在本文为您仔细讲解java 克隆对象的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:深度克隆,浅度克隆,区别,下面大家一起来学习吧。
在JAVA克隆对象不能简单的使用clone方法,clone方法只是进行浅克隆。请看下方:
深度克隆类:
Java代码
复制代码 代码如下:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class DepthClone {
    public  final static Object objectCopy(Object oldObj) {
        Object newObj = null;
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(oldObj);//源对象
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi= new ObjectInputStream(bi);
            newObj = oi.readObject();//目标对象
        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return newObj;
    }
}

浅度克隆类:
Java代码
复制代码 代码如下:

import java.io.Serializable;
public class SimpleClone implements Cloneable ,Serializable {
    private static final long serialVersionUID = -7552721152118950502L;

    public    String s = null;
    public Object o = null;
    public CloneObject cloneObject = null;

    
    public SimpleClone(CloneObject cloneObject) {
        this.cloneObject = cloneObject;
    }
    public Object clone() {
        SimpleClone newSimpleClone =  null;
        try {
            /* 浅克隆 */
            newSimpleClone = (SimpleClone)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return newSimpleClone;
    }
}

克隆对象:
Java代码
复制代码 代码如下:

import java.io.Serializable;

public class CloneObject implements Serializable{

    private static final long serialVersionUID = 4332788486669750696L;

    private String name ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

克隆测试:
Java代码
复制代码 代码如下:

public class TestClone {

    public static void main(String[] arg) {
        CloneObject obj1 = new CloneObject();
        obj1.setName("cloneOne");
        CloneObject obj2 = new CloneObject();
        obj2.setName("cloneTwo");

        SimpleClone simpleClone1 = new SimpleClone(obj1);
        SimpleClone simpleClone2 = new SimpleClone(obj2);

        simpleClone1.s = "simpleClone1";
        simpleClone1.o = "simpleClone1Object";

        //simpleClone2 = (SimpleClone)simpleClone1.clone();

        simpleClone2 = (SimpleClone)DepthClone.objectCopy(simpleClone1);

        /* 如果是浅克隆, simpleClone1中的cloneObject会随着simpleClone2的cloneObject改变面改变*/
        simpleClone2.cloneObject.setName("cloneThree");

        System.out.println(simpleClone1.cloneObject.getName());
        System.out.println(simpleClone2.cloneObject.getName());
    }

}

加载全部内容

相关教程
猜你喜欢
用户评论