欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java的深拷贝与浅拷贝的几种实现方式

程序员文章站 2022-09-26 10:20:47
1、介绍关于java的深拷贝和浅拷贝,简单来说就是创建一个和已知对象一模一样的对象。可能日常编码过程中用的不多,但是这是一个面试经常会问的问题,而且了解深拷贝和浅拷贝的原理,对于java中的所谓值传递...

1、介绍

关于java的深拷贝和浅拷贝,简单来说就是创建一个和已知对象一模一样的对象。可能日常编码过程中用的不多,但是这是一个面试经常会问的问题,而且了解深拷贝和浅拷贝的原理,对于java中的所谓值传递或者引用传递将会有更深的理解。

2、浅拷贝

浅拷贝就是获得拷贝对象的引用,而不是正真意义上的拷贝一个对象,例如

 a a = new a();
 a b = a;

此时引用变量a和b 同时指向了同一个堆中的内存空间,变量b只是复制了实例a的引用地址,并不是重新在堆中开辟了一个新的空间位置,来完整的复制实例a 如图

Java的深拷贝与浅拷贝的几种实现方式

3、深拷贝

深拷贝则是拷贝了源对象的所有值,所以即使源对象的值发生变化时,拷贝对象的值也不会改变。深拷贝则是真正意义上的拷贝,如图

Java的深拷贝与浅拷贝的几种实现方式

4、深拷贝和浅拷贝的区别

简单来说就是一句话: 深拷贝和浅拷贝最根本的区别在于是否真正获取一个对象的复制实体,而不是引用。

5、浅拷贝的实现

首先,我们定义一下需要拷贝的简单对象。

public class student{
 private string name; 
 private int age;  
 private string sex; 
}


public class school {
 private string schoolname;
 private int stunums;
 private student stu;
}

如上述代码,我们定义了一个student学生类,包含name姓名,和age年龄,sex性别,而是另一个school类,包含schoolname学校名称和stunums学生数量以及student学生,其中student并不是字符串,而是一个student类。接下来我们将详细描述如何签拷贝school对象。
我们看如下这段代码:

public class student{
  private string name;
  private int age;
  private string sex;
  
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  public string getsex() {
    return sex;
  }
  public void setsex(string sex) {
    this.sex = sex;
  }
  @override
  public string tostring() {
    return "student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
  }
}
public class school implements cloneable{
  private string schoolname;
  private int stunums;
  private student stu;
  
  public string getschoolname() {
    return schoolname;
  }
  public void setschoolname(string schoolname) {
    this.schoolname = schoolname;
  }
  public int getstunums() {
    return stunums;
  }
  public void setstunums(int stunums) {
    this.stunums = stunums;
  }
  public student getstu() {
    return stu;
  }
  public void setstu(student stu) {
    this.stu = stu;
  }
  @override
  protected school clone() throws clonenotsupportedexception {
    // todo auto-generated method stub
    return (school)super.clone();
  }
  @override
  public string tostring() {
    return "school [schoolname=" + schoolname + ", stunums=" + stunums + ", stu=" + stu + "]";
  }
}

这是一个我们要进行赋值的原始类 school。下面我们产生一个 school对象,并调用其 clone 方法复制一个新的对象。
注意:调用对象的 clone 方法,必须要让类实现 cloneable 接口,并且覆写 clone 方法。

public class testclone {
  public static void main(string[] args) throws clonenotsupportedexception {
    //创建初始的school对象
    school s1 = new school();
    s1.setschoolname("xx大学");
    s1.setstunums(2000);
    student stu1 = new student();
    stu1.setage(20);
    stu1.setname("肉丁");
    stu1.setsex("女");
    s1.setstu(stu1);
    school s2 = s1.clone(); //调用重写的clone方法,clone出一个新的school---s2
    system.out.println("s1: "+s1+" s1的hashcode:"+s1.hashcode()+" s1中stu1的hashcode:"+s1.getstu().hashcode());
    system.out.println("s2: "+s2+" s2的hashcode:"+s2.hashcode()+" s2中stu1的hashcode:"+s2.getstu().hashcode());//system.out.println(s1.getstu().getage()==s2.getstu().getage());
    system.out.println("----------------------------");
    system.out.println("修改克隆出来的对象");
    student student2 = s2.getstu();
    student2.setage(21);
    student2.setname("斌");
    s2.setstu(student2);
    system.out.println("s1: "+s1+" s1的hashcode:"+s1.hashcode()+" s1中stu1的hashcode:"+s1.getstu().hashcode());
    system.out.println("s2: "+s2+" s2的hashcode:"+s2.hashcode()+" s2中stu1的hashcode:"+s2.getstu().hashcode());//system.out.println(s1.getstu().getage()==s2.getstu().getage());
  }
}

我们查看输出的结果

s1: school [schoolname=xx大学, stunums=2000, stu=student [name=肉丁, age=20, sex=女]]
s1的hashcode:500977346
s1中stu1的hashcode:20132171
s2: school [schoolname=xx大学, stunums=2000, stu=student [name=肉丁, age=20, sex=女]]
s2的hashcode:186370029
s2中stu1的hashcode:20132171
修改克隆出来的对象
s1: school [schoolname=xx大学, stunums=2000, stu=student [name=斌, age=21, sex=女]]
s1的hashcode:500977346
s1中stu1的hashcode:20132171
s2: school [schoolname=xx大学, stunums=2000, stu=student [name=斌, age=21, sex=女]]
s2的hashcode:186370029
s2中stu1的hashcode:20132171

首先看原始类 school 实现 cloneable 接口,并且覆写 clone 方法,它还有三个属性,一个引用类型 string定义的 schoolname,一个基本类型 int定义的 stunums,还有一个引用类型 student,这是一个自定义类,这个类也包含三个属性 name、age和 sex。

接着看测试内容,首先我们创建一个school类的对象s1 ,其schoolname为xx大学,stunums为2000,学生类stundet三个属性为 20、肉丁和女。接着我们调用 clone() 方法复制另一个对象 s2,接着打印这两个对象的内容。

从第 2 行和第 5 行打印结果:

s1的hashcode:500977346
s2的hashcode:186370029

可以看出这是两个不同的对象。

从第 1 行和第 4 行打印的对象内容看,原对象 s1 和克隆出来的对象 s2 内容完全相同。

代码中我们只是更改了克隆对象 s2 的属性student 为斌、21、女(原对象 s1 是肉丁、20、女) ,但是从第 8 行和第 11 行打印结果来看,原对象 s1 和克隆对象 s2 的 student属性都被修改了。

也就是说对象 school的属性 student,经过 clone 之后,其实只是复制了其引用,他们指向的还是同一块堆内存空间,当修改其中一个对象的属性 student,另一个也会跟着变化。

6、深拷贝的实现

深拷贝的方式有很多种,文中我们将介绍三种方式

  • 方法一 构造函数
  • 方法二 重载clone()方法
  • 方法三serializable序列化

6.1、构造函数

public void constructorcopy() {
 
  student student = new student ("小李",21,"男");
  school school = new school ("xx大学",100, student);
 
  // 调用构造函数时进行深拷贝
  school copyschool = new school (school.getschoolname(),school.getstunums(), new student(student.getname(), student.getage(),student.getsex()));
 
  // 修改源对象的值
  copyschool .getstudent().setsex("女");
 
  // 检查两个对象的值不同
  system.out.println(school.hashcode()==school2.hascode())
 
}

6.2、重载clone()方法

object父类有个clone()的拷贝方法,不过它是protected类型的,我们需要重写它并修改为public类型。除此之外,子类还需要实现cloneable接口来告诉jvm这个类是可以拷贝的。让我们还是看之前的school代码

public class school implements cloneable{
  private string schoolname;
  private int stunums;
  private student stu;
  public string getschoolname() {
    return schoolname;
  }
  public void setschoolname(string schoolname) {
    this.schoolname = schoolname;
  }
  public int getstunums() {
    return stunums;
  }
  public void setstunums(int stunums) {
    this.stunums = stunums;
  }
  public student getstu() {
    return stu;
  }
  public void setstu(student stu) {
    this.stu = stu;
  }
  @override
  protected school clone() throws clonenotsupportedexception {
    school school = (school) super.clone();
    school.stu = (student) stu.clone();
    return school;
  }
  @override
  public string tostring() {
    return "school [schoolname=" + schoolname + ", stunums=" + stunums + ", stu=" + stu + "]";
  }
}

public class student implements cloneable{
  private string name;
  private int age;
  private string sex;
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  public string getsex() {
    return sex;
  }
  public void setsex(string sex) {
    this.sex = sex;
  }
  @override
  public string tostring() {
    return "student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
  }
  @override
  protected student clone() throws clonenotsupportedexception {
    return (student)super.clone();
  }
}

我们查看输出的结果

s1: school [schoolname=xx大学, stunums=2000, stu=student [name=肉丁, age=20, sex=女]]
s1的hashcode:500977346
s1中stu1的hashcode:20132171
s2: school [schoolname=xx大学, stunums=2000, stu=student [name=肉丁, age=20, sex=女]]
s2的hashcode:186370029
s2中stu1的hashcode:2094548358
修改克隆出来的对象
s1: school [schoolname=xx大学, stunums=2000, stu=student [name=肉丁, age=20, sex=女]]
s1的hashcode:500977346
s1中stu1的hashcode:20132171
s2: school [schoolname=xx大学, stunums=2000, stu=student [name=斌, age=21, sex=女]]
s2的hashcode:186370029
s2中stu1的hashcode:2094548358

需要注意的是,super.clone()其实是浅拷贝,所以在重写school类的clone()方法时,student对象需要调用stu.clone()重新赋值。
查看第 2 行和第 5 行

s1的hashcode:500977346
s2的hashcode:186370029

查看第 3 行和第 6 行

s1中stu1的hashcode:20132171
s2中stu1的hashcode:2094548358

通过结果发现重新复制的对象s2和s1的hashcode不同,并且s1.stu与s2.stu2的hashcode也不同,由此证明复制的新的对象和原本的对象指向的不是同一个一个对象,意味着堆内存中存在两个school实例

6.3、serializable序列化

我们看如下的代码

import java.io.serializable;
public class user implements serializable {

  private string name;
  private address2 address;

  public user(string name, address2 address) {
    this.name = name;
    this.address = address;
  }

  public string getname() {
    return name;
  }

  public void setname(string name) {
    this.name = name;
  }

  public address2 getaddress() {
    return address;
  }

  public void setaddress(address2 address) {
    this.address = address;
  }
  public object deepclone() throws exception
  {
    // 序列化
    bytearrayoutputstream bos = new bytearrayoutputstream();
    objectoutputstream oos = new objectoutputstream(bos);

    oos.writeobject(this);

    // 反序列化
    bytearrayinputstream bis = new bytearrayinputstream(bos.tobytearray());
    objectinputstream ois = new objectinputstream(bis);

    return ois.readobject();
  }
}
import java.io.serializable;
public class address2 implements serializable {
  private string city;
  private string country;

  public address2(string city, string country) {
    this.city = city;
    this.country = country;
  }

  public string getcity() {
    return city;
  }

  public void setcity(string city) {
    this.city = city;
  }

  public string getcountry() {
    return country;
  }

  public void setcountry(string country) {
    this.country = country;
  }

  @override
  public string tostring() {
    return "address2{" +
        "city='" + city + '\'' +
        ", country='" + country + '\'' +
        '}';
  }
}

注意 要使用序列化的方式来复制对象 对象需要继承serializable接口,接下来我们查看测试类

public static void main(string[] args) throws exception {
    address2 address = new address2("大同", "中国");
    user user = new user("yznl", address);
    user user2 = (user) user.deepclone();
    system.out.println(user.tostring());
    system.out.println(user2.tostring());

  }

结果如下:

277630005,1915503092

通过比较user对象和克隆的user2对象的hashcode发现,也是不同的对象

到此这篇关于java的深拷贝与浅拷贝的几种实现方式的文章就介绍到这了,更多相关java 深拷贝与浅拷贝内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!