Java 的深拷贝和浅拷贝

基本知识

Java在运行时的内存使用分两块:栈内存与堆内存。

只就变量而言,栈内存上分配一些基本类型的变量(如intboolean)与对象的引用,而堆内存分配给真正的对象本身以及数组等,堆内存上的数据由栈内存上的相应变量引用,相当于栈中存储着堆内存中实际对象或数组的标记或别名(实际上是堆内存变量首地址)。

什么是拷贝

将对象复制出一份的行为称为对象的拷贝。

一般来说,拷贝出的对象需要满足以下三点:

  • x.clone() != x
  • x.clone().getClass() == x.getClass()
  • x.clone().equals(x)

首先定义三个类。

PersonalInfo.java

      
      
1
2
3
4
5
6
      
      
public class PersonalInfo implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

Manager.java

      
      
1
2
3
4
5
6
7
8
9
10
      
      
public class Manager implements Cloneable {
private PersonalInfo personalInfo;
/* 省略 constructor 与 accessors */
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

Department.java

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
public class Department implements Cloneable {
private int empCount;
private Manager manager;
/* 省略 constructor 与 accessors */
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

当需要被克隆的对象的类没有实现Cloneable接口而被调用clone方法时,就会抛出CloneNotSupportedException

再在Main类中编写测试用的断言,本文将面向测试一步一步地实现最终的彻底深拷贝

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
      
      
Department dep0 = new Department( 100, new Manager( new PersonalInfo()));
Department dep1;
// do something here
/* 是浅拷贝 */
assert dep0 != dep1;
/* 是深拷贝 */
assert dep0.getManager() != dep1.getManager();
/* 是彻底深拷贝 */
assert dep0.getManager().getPersonalInfo() != dep1.getManager().getPersonalInfo();

为了使断言机制工作,我们在运行/调试配置中传入VM参数-enableassertions

主要有两种约定俗成的形式来实现拷贝,本文选择clone()

clone方法

Object.class

      
      
1
2
3
      
      
// ...
protected native Object clone() throws CloneNotSupportedException;
// ...

protected表示该方法只能在本身、本包以及子类中使用。

new关键字

这种方式与重写clone()大同小异,唯一不同的是new关键字直接开辟了新对象,继而只需要完成相应字段的拷贝工作。

传引用

在学习编写Java代码的过程中,最常见的问题就是String的“相等”,以此为思路,首先尝试:

      
      
1
      
      
dep1 = dep0;

断言失败在assert dep0 != dep1;,说明dep0dep1根本就是引用了堆上的同一个对象,拷贝也就更无从谈起了。

同一引用

同一引用

浅拷贝

在没有显式重写Department类的clone方法时,尝试:

      
      
1
      
      
dep1 = (Department) dep0.clone();

断言失败在assert dep0.getManager() != dep1.getManager();,说明

相关文章
相关标签/搜索