When we do object’s cloning by default it is a shallow copy. But to achieve a deep copy the classes must be edited or adjusted. Below is the object example where it shows the difference between shallow cloning and deep cloning.
In example Fig 1 shows the original object contains (refers) object 1 and object 2. When a shallow copy is performed on object 1 as shown in fig 2 then it is copied but its contained objects are not. The contained objects Object 1 and Object 2 are affected by changes to cloned Object 2. Java supports shallow cloning of objects by default when a class implements the java.lang. Cloneable interface.
浅复制对象中包含(指向)的对象并没用复制,实现java.lang. Cloneable接口的对象的clone是浅复制
When a deep copy is performed on object 1 as shown in fig3 then not only object1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.
而深复制则是将复合对象包含(指向)的成员也复制了,通过序列化/反序列化得到的就是深复制的对象,不过对性能有影响
For example, invoking clone() method on a collection like HashMap, List etc returns a shallow copy of HashMap, List, instances. This means if you clone a HashMap, the map instance is cloned but the keys and valuesthemselves are not cloned. If you want a deep copy then a simple method is to serialize the HashMap to aByteArrayOutputSream and then deserialize it. This creates a deep copy but does require that all keys and valuesin the HashMap are Serializable.
调用Map、List的clone方法时返回浅复制的对象,意味着当你clone一个HashMap时,map的实例复制了,但是其中的key和value并没用被复制
I hope this will clear difference between shallow cloning and deep cloning
没有评论:
发表评论