gpt4 book ai didi

java - java中如何进行浅克隆和深克隆?

转载 作者:行者123 更新时间:2023-12-02 02:52:53 26 4
gpt4 key购买 nike

我在包 pack1 中有三个类。这三个类是 classA classBclassC

A 类

public class Address {
public String town = null;
public String street = null;
public int postCode = 0;
public int houseNumber = 0;
}

B 类

public class Course {
public String number;
public String name;

public Course(){
number = null;
name = null;
}

C类

public class Student {
public Date dob;
public Course course = new Course();
public Address address = new Address();


public Student(){
dob = null;
course.name = null;
course.number = null;
address.town = null;
address.street = null;
address.postCode = 0;
address.houseNumber = 0;
course.name = null;
course.number = null;

}

我想知道如何进行深度克隆地址和 dob 以及浅层克隆过程?我还不知道如何进行克隆组合

最佳答案

浅复制:对象的浅拷贝将具有原始对象所有字段的精确副本。如果原始对象将其他对象作为字段引用,则仅将这些对象的引用复制到克隆对象中,而不会创建这些对象的副本。

深复制:对象的深复制将像浅复制一样精确复制原始对象的所有字段。但此外,如果原始对象有任何对其他对象作为字段的引用,那么这些对象的副本也会通过调用它们的clone()方法来创建

由于类(class)实体没有任何对象引用,因此使用默认克隆方法对其进行克隆。学生实体作为日期、类(class)、地址的引用,我们需要重写克隆方法。下面是示例代码:-

public static class Address implements Cloneable{
public String town = null;
public String street = null;
public int postCode = 0;
public int houseNumber = 0;

public Address(String town , String street ,int postCode , int houseNumber){
this.town = town;
this.street = street;
this.postCode = postCode;
this.houseNumber = houseNumber;
}
public Address(){
}

//Default version of clone() method. It creates shallow copy of an object.

protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

public static class Course implements Cloneable{
public String number;
public String name;

public Course(){
number = null;
name = null;
}

public Course(String number , String name){
this.number = number;
this.name = name;
}

//Default version of clone() method. It creates shallow copy of an object.

protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}

}

public static class Student implements Cloneable{
public Date dob;
public Course course = new Course();
public Address address = new Address();



public Student(){
dob = null;
course.name = null;
course.number = null;
address.town = null;
address.street = null;
address.postCode = 0;
address.houseNumber = 0;

}

public Student(Date dob , Course course , Address address){
this.dob = dob;
this.course = course;
this.address = address;
}

protected Object clone() throws CloneNotSupportedException
{
Student student = (Student) super.clone();

student.course = (Course) course.clone();
student.address = (Address) address.clone();
student.dob = (Date) dob.clone();

return student;
}
}

关于java - java中如何进行浅克隆和深克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43534163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com