Java Clone, Shallow Copy and Deep Copy
2015-09-25 14:46
369 查看
In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones. If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory method and provide it with a good documentation. When you are in a situation to use a third party component and produce copies of it using the clone method, then investigate that implementation carefully and get to know what is underlying. Because when you ask for a rabbit, it may give monkeys!
Since the Object class has the
One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take
When implementing a singleton pattern, if its superclass implements a public
Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.
Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.
Example source code for java clone and shallow copy
Output of the above program:
Shallow Copy
Generallyclonemethod of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a
clonemethod and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.
Since the Object class has the
clonemethod (protected) you cannot use it in all your classes. The class which you want to be cloned should implement
clonemethod and overwrite it. It should provide its own meaning for copy or to the least it should invoke the
super.clone(). Also you have to implement
Cloneablemarker interface or else you will get
CloneNotSupportedException. When you invoke the
super.clone()then you are dependent on the Object class’s implementation and what you get is a shallow copy.
Deep Copy
When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take
List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like
ArrayListby name. This completely removes the advantage and goodness of abstractness.
When implementing a singleton pattern, if its superclass implements a public
clone()method, to prevent your subclass from using this class’s
clone()method to obtain a copy overwrite it and throw an exception of type
CloneNotSupportedException.
Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.
Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.
Example source code for java clone and shallow copy
class Employee implements Cloneable { private String name; private String designation; public Employee() { this.setDesignation("Programmer"); } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object clone() throws CloneNotSupportedException { /* Employee copyObj = new Employee(); copyObj.setDesignation(this.designation); copyObj.setName(this.name); return copyObj; */ return super.clone(); } } public class CloneExample { public static void main(String arg[]){ Employee jwz = new Employee(); jwz.setName("Jamie Zawinski"); try { Employee joel = (Employee) jwz.clone(); System.out.println(joel.getName()); System.out.println(joel.getDesignation()); } catch (CloneNotSupportedException cnse) { System.out.println("Cloneable should be implemented. " + cnse ); } } }
Output of the above program:
Jamie Zawinski Programmer
相关文章推荐
- JAVA反射例子
- An internal error occurred during: "Initializing Java Tooling".
- Java基础知识强化85:System类之arraycopy()方法(数组拷贝)
- Java产生随机数和随机字母的方法
- binbinyang---eclipse中show whitespace characters按钮编辑器中显示导致恶心的乱码
- java的system.arraycopy()方法
- 浅论Maven和Git的原理及展示其与Eclipse的集成
- java编译找不到符号
- struts2 no extension(excludePattern)
- test7.7
- 利用Java生成静态HMTL页面
- Java jni使用
- java基础-java零散知识
- 解决 maven 工程导入 eclipse 后的问题
- myeclipse6.5 注册机
- 用java写一个main函数实现排列组合
- java线程同步
- java socket简单实例练习
- test7.6
- Java中的值传递和引用传递