[英]shallow copy and deep copy example
Can i implement deep copy and shallow copy in following way?Is it correct? 我可以通过以下方式实现深层复制和浅层复制吗? Any one on the following 2 clone methods would be placed in final code
以下2个克隆方法中的任何一个都将放置在最终代码中
public class Student{
private String name;
private DepartMent dept;
//deep copy
public Object clone() throws CloneNotSupportedException{
Student s = (Student)super.clone();
s.septDept((Department)dept.clone());
}
//shallow copy
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
Instead of attempting to implement Cloneable
, which is considered broken , I would recommend you look at using copy constructors . 我不建议您尝试实现被认为已损坏的
Cloneable
,而是建议您使用复制构造函数 。 A copy constructor takes an instance of its own declaring type as an argument, and copies that instance's fields to the new object. 复制构造函数将其声明类型的实例作为参数,然后将该实例的字段复制到新对象。 For example:
例如:
public Student(Student copyFrom) {
this.name = copyFrom.name;
this.dept = copyFrom.dept;
}
...
Student copy = new Student(originalStudent);
If Department
also exposes a copy constructor, this will allow you to make a deep copy of Student
. 如果
Department
也公开了副本构造函数,则可以复制Student
的深层副本。 For example: 例如:
public Student(Student copyFrom) {
this.name = copyFrom.name;
this.dept = new Department(copyFrom.dept);
}
Although it's unclear from your question why a deep copy is necessary. 尽管您的问题尚不清楚,为什么需要深拷贝。
For further reading, this article touches on both the issues of Cloneable
and the limitations of copy constructors. 为了进一步阅读, 本文同时介绍了
Cloneable
和复制构造函数的局限性。
根据我的理解,是正确的,您只需要确保一件事,即在DepartMent类中覆盖clone()方法。
您还可以使用dup()方法,该方法还返回原始副本,具体取决于您尝试使用copy方法实现的代码类型...您只是在寻求建议,而没有提供足够的信息以正确指导您...在stackoverflow中也有很多回答问题的例子,因此您应该在寻求附加帮助之前先对它进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.