javaの深度コピーと浅いコピー

2648 ワード

浅いコピー:オブジェクトをコピーすると、基本的なデータタイプの変数が再作成されます。参照タイプ、オブジェクトが指すもの、または元のオブジェクトが指すものです。
深度コピー:一つのオブジェクトをコピーした後、基本データの種類や参照の種類を問わず、新たに作成します。
深くコピーするキーを実現します。オブジェクトのバイナリ表現をストリーム形式で読み、書きます。
テストコードは以下の通りです。
Clone:
package com.study.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Clone implements Cloneable, Serializable {
	
	private Child child;
	
	public Clone() {}
	
	public Clone(Child child) {
		this.child = child;
	}

	/**
	 *        
	 *    :        ,               ,     ,            
	 * @param o
	 * @return
	 * @throws CloneNotSupportedException
	 */
	public Object lightClone() throws CloneNotSupportedException {
		Object newObject = null;
		newObject = super.clone();
		return newObject;
	}
	
	/**
	 *        
	 *    :         ,               ,       
	 * @param o
	 * @return
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public Object deepClone() throws IOException, ClassNotFoundException {
		Object newObject = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		//      bos  
		oos.writeObject(this);
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		newObject = ois.readObject();
		return newObject;
	}
	
	public Child getChild() {
		return child;
	}
	
	public void setChild(Child child) {
		this.child = child;
	}
	
	public static void main(String[] args) {
		Clone clone0 = new Clone(new Child("child0"));
		Child child0 = clone0.getChild();
		//      
		try {
			Clone clone1 = (Clone)clone0.lightClone();
			Child child1 = clone1.getChild();
			if(child0 == child1) {
				System.out.println("   ");
			}
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		
		//      
		try {
			Clone clone2 = (Clone) clone0.deepClone();
			Child child2 = clone2.getChild();
			if(child0 != child2) {
				System.out.println("   ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}
Child:
package com.study.clone;

import java.io.Serializable;

public class Child implements Serializable {
	
	private String name;
	
	public Child() {}
	
	public Child(String name) {
		this.name = name;
	}
	
	public String getName() {
		return this.name;
	}

}
結果出力: