`

Java中的深拷贝与浅拷贝

阅读更多
在Java中,一个重要的,而且是每个类都有的方法,clone()。在克隆中,众所周知的一个方面便是深克隆与浅克隆问题。如果是基本数据类型或者String的话,那么简单的浅克隆便可以实现需要的功能。但是当遇到对象类型,包括数组,类等等,则必须使用深克隆的方法来进行。下面举出例子来说明深克隆和浅克隆的区别:

package com.java.lang;

import java.util.Arrays;

public class CLONE implements Cloneable {
	
	private int value;
	private int[] array;
	private Person person;

	public CLONE(int value, int[] array, Person person) {
		this.value = value;
		this.array = array;
		this.person = person;
	}


	@Override
	protected Object clone(){
		CLONE o = null;
		try {
			o = (CLONE)super.clone();
			o.person = (Person)this.person.clone();
			o.array = new int[this.array.length];
			for(int i=0;i<this.array.length;i++){
				o.array[i] = this.array[i];
			}
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return o;
	}


	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public int[] getArray() {
		return array;
	}

	public void setArray(int[] array) {
		this.array = array;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	@Override
	public String toString() {
		String result = "";
		
		result += "\tvalue: " + value + "\n";
		result += "\tarray: " + Arrays.toString(array) + "\n";
		result += "\tperson: " + person.getName();
		
		return result;
	}


	public static void main(String[] args) {
		int[] input1 = {1,2,3,4,5};
		Person paul = new Person("paul");
		
		CLONE clone1 = new CLONE(5, input1,paul);
		CLONE clone2 = (CLONE)clone1.clone();
		
		System.out.println("clone1:\n" + clone1);
		System.out.println("clone2:\n" + clone2);
		
		clone1.getPerson().setName("eric");
		System.out.println("clone1:\n" + clone1);
		System.out.println("clone2:\n" + clone2);
		
		
		clone1.getArray()[0] = 0;
		System.out.println("clone1:\n" + clone1);
		System.out.println("clone2:\n" + clone2);
	}
}

class Person implements Cloneable{
	private String name = "";

	public Person(String name) {
		super();
		this.name = name;
	}
	
	protected Object clone(){
		Object o = null;
		try {
			o = super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return o;
	}



	public String getName() {
		return name;
	}

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



结果:

clone1:
value: 5
array: [1, 2, 3, 4, 5]
person: paul
clone2:
value: 5
array: [1, 2, 3, 4, 5]
person: paul
clone1:
value: 5
array: [1, 2, 3, 4, 5]
person: eric
clone2:
value: 5
array: [1, 2, 3, 4, 5]
person: paul
clone1:
value: 5
array: [0, 2, 3, 4, 5]
person: eric
clone2:
value: 5
array: [1, 2, 3, 4, 5]
person: paul
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics