浅谈Java的浅克隆和深克隆

浅谈Java的浅克隆和深克隆

为什么要使用克隆?

Object类提供的clone()方法不仅能简单地处理"复制"对象的问题,而且这种"自我克隆"机制十分高效,比如clone一个包含1000个元素的int[]数组,用系统默认的clone方法比静态copy方法快近2倍.

自定义类如何实现"克隆"?

自定义类实现"克隆"有三步:
  1. 自定义类实现Cloneable接口.(这是一个标记性接口,实现该接口的对象可以实现"自我克隆",接口里没有定义任何方法)
  2. 自定义类实现自己的clone()方法.(覆盖clone()方法,访问修饰符设为public,默认是protected)
  3. 实现clone()方法时通过super.clone()调用Object实现的clone()方法来得到该对象的副本,并返回该副本.

克隆的方法有两种:浅克隆(ShallowClone)和深克隆(DeepClone)

浅克隆是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象.
深克隆不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象.

浅克隆示意图:

浅克隆示意图

深克隆示意图:

深克隆示意图

浅克隆

public class CloneTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        User u1 = new User(28);
        // clone得到u1对象的副本
        User u2 = u1.clone();
        // 判断u1,u2是否相同
        System.out.println(u1 == u2);// ①
        // 判断u1,u2的address是否相同
        System.out.println(u1.address == u2.address);// ②
    }
}

class User implements Cloneable {
    int age;
    Address address;

    public User(int age) {
        super();
        this.age = age;
        this.address = new Address("北京");
    }

    // 通过super.clone()来实现clone方法
    public User clone() throws CloneNotSupportedException {
        return (User) super.clone();
    }
}

class Address {
    String detail;
    public Address(String detail) {
        super();
        this.detail = detail;
    }
}
运行结果:
false
true

程序在①处可得知,原有的User对象与克隆出来的User对象不是同一个,判断返回了false,说明不是同一个对象.

Object类提供的Clone机制只对对象里各实例变量进行"简单复制",如果实例变量的类型是引用类型,Object的Clone机制也只是简单的复制这个引用变量,这样原有对象的引用类型的实例变量与被克隆对象的引用类型的实例变量依然指向内存中的同一个实例,所以上面程序中②处代码输出true,上面程序"克隆"出来的u1,u2所指向的对象在内存中的存储如浅克隆示意图所示:

如果需要对对象进行"深克隆",则需要开发者自己进行"递归"克隆,保证所有引用类型的成员变量值所引用的对象都被复制,如下代码:

深克隆

public class CloneTest {
	
	public static void main(String[] args) throws CloneNotSupportedException {	
		User u1 = new User(28);
		//clone得到u1对象的副本
		User u2 = u1.clone();
		//判断u1,u2是否相同
		System.out.println(u1 == u2);// ①
		//判断u1,u2的address是否相同
		System.out.println(u1.address == u2.address);	// ②
	}
}

class User implements Cloneable{
	int age;
	Address address;
	
	public User(int age) {
		super();
		this.age = age;
		this.address = new Address("北京");	
	}
	//通过super.clone()来实现clone方法
	public User clone() throws CloneNotSupportedException{
		User user = (User)super.clone();
		user.address = address.clone();//这两步就是进行深克隆
		return user;
	}	
}

class Address implements Cloneable{
	String detail;
	public Address(String detail) {	
		super();
		this.detail = detail;	
	}
	//通过super.clone()来实现clone方法
		public Address clone() throws CloneNotSupportedException{
			return (Address)super.clone();
		}	
}
运行结果:
false
false

上面程序代码①和②处都返回了false,说明对象和对象的引用是两个对象.说明"克隆"成功.

理解上面代码一定可以掌握浅克隆(ShallowClone)深克隆(DeepClone).

深克隆例子
public class DeepClone {

	public static void main(String[] args) throws CloneNotSupportedException {
		
		People people1 = new People();
		people1.setName("小明");
		people1.setGender("男");
		Person person1 = new Person();
		person1.setName("张三");
		person1.setPeople(people1);
		
		Person person2 = (Person)person1.clone();
		person2.setName("李四");
		People people2 = person2.getPeople();
		people2.setName("小花");
		people2.setGender("女");
		
		System.out.println("person1 : " + person1);
		System.out.println("person2 : " + person2);
		
	}
	
}


class Person implements Cloneable{
	
	private String name;
	
	private People people;
	
	
	public String getName() {
		return name;
	}

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

	public People getPeople() {
		return people;
	}

	public void setPeople(People people) {
		this.people = people;
	}
	
	@Override
		public String toString() {
			return "Person 姓名:"+name+"  People=[ "+people +"]";
		}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		
		Person person = (Person)super.clone();
		
		person.setPeople((People)person.getPeople().clone());
		
		return person;
	}
	
}


class People implements Cloneable{
	
	private String name;
	private String gender;
	
	public People(){
		
	}
	
	public People(String name,String gender){
		this.name=name;
		this.gender=gender;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
	@Override
	public String toString() {
		return "People 姓名= "+name+"  People 性别= "+gender;
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	
}

运行结果:
person1 : Person 姓名:张三  People=[ People 姓名= 小明  People 性别= 男]
person2 : Person 姓名:李四  People=[ People 姓名= 小花  People 性别= 女]

参照上面例子输出的结果进行理解"深克隆".

发布了4 篇原创文章 · 获赞 5 · 访问量 153

猜你喜欢

转载自blog.csdn.net/wcf_hrkj/article/details/103370557