深度复制和浅复制的区别是什么?


当前回答

“ShallowCopy”指向与“Source”相同的内存位置。“DeepCopy”指向内存中的不同位置,但内容是相同的。

其他回答

浅克隆: 定义:“对象的浅拷贝复制‘主’对象,但不复制内部对象。” 当一个自定义对象(例如。雇员)只有原始的,字符串类型的变量,然后你使用浅克隆。

Employee e = new Employee(2, "john cena");
Employee e2=e.clone();

返回super.clone();在重写的clone()方法中,您的工作就结束了。

深克隆: 定义:“与浅拷贝不同,深拷贝是对象的完全独立副本。” 表示当一个Employee对象持有另一个自定义对象时:

Employee e = new Employee(2, "john cena", new Address(12, "West Newbury", "Massachusetts");

然后,您必须在覆写的clone()方法中编写代码来克隆'Address'对象。否则Address对象不会被克隆,当你在克隆的Employee对象中改变Address的值时,它会导致一个错误,这也反映了原始的一个。

试着考虑下面的图像

例如Object。memberwisclone创建一个浅复制链接

并使用ICloneable接口,你可以得到深度拷贝,如这里所述

浅复制-原始和浅复制对象中的引用变量引用公共对象。

深度复制-原始和深度复制对象中的引用变量引用不同的对象。

克隆总是做浅拷贝。

public class Language implements Cloneable{
    
    String name;
    public Language(String name){
        this.name=name;
    }
    
    public String getName() {
        return name;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

主类如下-

public static void main(String args[]) throws ClassNotFoundException, CloneNotSupportedException{

      ArrayList<Language> list=new ArrayList<Language>();
      list.add(new Language("C"));
      list.add(new Language("JAVA"));

      ArrayList<Language> shallow=(ArrayList<Language>) list.clone();
      //We used here clone since this always shallow copied.

      System.out.println(list==shallow);
      
      for(int i=0;i<list.size();i++)
      System.out.println(list.get(i)==shallow.get(i));//true
      
      ArrayList<Language> deep=new ArrayList<Language>();
      for(Language language:list){
          deep.add((Language) language.clone());
      }
      System.out.println(list==deep);
      for(int i=0;i<list.size();i++)
          System.out.println(list.get(i)==deep.get(i));//false
      
} 

以上输出为-

假真假真 假假假

原始物体的任何变化都将反映在浅物体上,而不是在深物体上。

  list.get(0).name="ViSuaLBaSiC";
  System.out.println(shallow.get(0).getName()+"  "+deep.get(0).getName());

输出- ViSuaLBaSiC C

我在这里没有看到一个简短的,容易理解的答案——所以我会试一试。

使用浅拷贝,源指向的任何对象也会被目标指向(因此不会复制引用的对象)。

使用深度复制,源指向的任何对象都将被复制,而目标指向的副本(因此现在每个引用的对象都有2个)。这是递归向下的对象树。

The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the article C++ constructors.