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


当前回答

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

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

克隆总是做浅拷贝。

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

其他回答

浅拷贝:将成员值从一个对象复制到另一个对象。

深度复制:将成员值从一个对象复制到另一个对象。                       任何指针对象复制和复制。

例子:

class String
{
     int   size;
     char* data;
};

String  s1("Ace");   // s1.size = 3 s1.data=0x0000F000

String  s2 = shallowCopy(s1);
 // s2.size =3 s2.data = 0X0000F000
String  s3 = deepCopy(s1);
 // s3.size =3 s3.data = 0x0000F00F
 //                      (With Ace copied to this location.)

尤其是iOS开发者:

如果B是a的浅拷贝,那么对于原语数据,它就像B = [a assign];对于对象,B = [A retain];

B和A指向同一个内存位置

如果B是a的深层副本,则B = [a copy];

B和A指向不同的内存位置

B的内存地址与A的相同

B和A的含量相同

假设有两个数组arr1和arr2。

arr1 = arr2;   //shallow copy
arr1 = arr2.clone(); //deep copy

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.

试着考虑下面的图像

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

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