Deep diving into Cloning

文章摘自http://idiotechie.com/Mainak Goswami的blog

首先来查看下heap如何分配Object


Deep diving into Cloning

这并非clone,这只是把对象引用共享性质了。

 

What is cloning?

clone就是把自己给复制所有东西倾囊相授,但是又不是它自己,是不同个体。如同黑哥帝国中所有的黑衣人都是独立个体,但是同是具有同一的能力。

public class CloneStyle {

	/**
	 * @param args
	 * @throws CloneNotSupportedException
	 */
	public static void main(String[] args) throws CloneNotSupportedException {

		Person p1 = new Person();
		Person p2 = (Person) p1.clone();
		System.out.println(p1 != p2);
		System.out.println(p1.getClass() == p2.getClass());
		System.out.println(p1.equals(p2));
	
	}

}

 
 让我们探讨下:

true:代表他们在独立的个体,在内存中分配不同地址

true:代表他们虽然是独立个体,但是他们是来源于同一类型

false:不同对象

 

Shallow Cloning vs Deep Cloning

clone支持Shallow Cloning vs Deep Cloning

shallow只是提供了primitive type的copy,而对于引用类型的Object并不支持


Deep diving into Cloning
 
Deep diving into Cloning
 


Deep diving into Cloning
 shallow cloing的使用主要是通过Cloneable下clone的方法

public class Person implements Cloneable {

	@Override
	protected Object clone() throws CloneNotSupportedException {
		Person o = null;
		try {
			o = (Person) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return o;
	}

	private int age;
	private String name;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

}

 Deep Cloning


Deep diving into Cloning
 
Deep diving into Cloning
 

public Object clone() {
	//Deep Copy process
		Employee e = new Employee(employeeName, dept.getDeptName());
		return e;
}

 采用new操作,重新复制了一遍。

你可能感兴趣的:(div)