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


当前回答

简而言之,这取决于什么指向什么。在浅拷贝中,对象B指向对象a在内存中的位置。在深度复制中,对象A的内存位置中的所有东西都被复制到对象B的内存位置。

这篇wiki文章有一个很好的图表。

http://en.wikipedia.org/wiki/Object_copy

其他回答

为了便于理解,你可以参考这篇文章: https://www.cs.utexas.edu/~scottm/cs307/handouts/deepCopying.htm


浅拷贝:


深拷贝:

在面向对象编程中,类型包括成员字段的集合。这些字段可以按值或引用(即指向值的指针)存储。

在浅复制中,将创建该类型的新实例,并将值复制到新实例中。引用指针也像值一样被复制。因此,引用指向原始对象。对引用存储的成员的任何更改都同时出现在原始和副本中,因为没有对引用的对象进行复制。

在深度复制中,像以前一样复制按值存储的字段,但不复制按引用存储的对象指针。相反,对引用的对象进行深度复制,并存储指向新对象的指针。对这些引用对象所做的任何更改都不会影响该对象的其他副本。

char * Source = "Hello, world.";

char * ShallowCopy = Source;    

char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);        

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

浅拷贝不会创建新的引用,但深拷贝会创建新的引用。

下面是程序解释的深拷贝和浅拷贝。

public class DeepAndShollowCopy {
    int id;
    String name;
    List<String> testlist = new ArrayList<>();

    /*
    // To performing Shallow Copy 
    // Note: Here we are not creating any references. 
      public DeepAndShollowCopy(int id, String name, List<String>testlist)
       { 

       System.out.println("Shallow Copy for Object initialization");
       this.id = id; 
       this.name = name; 
       this.testlist = testlist; 

       }
    */  

    // To performing Deep Copy 
    // Note: Here we are creating one references( Al arraylist object ). 
    public DeepAndShollowCopy(int id, String name, List<String> testlist) {
        System.out.println("Deep Copy for Object initialization");
        this.id = id;
        this.name = name;
        String item;
        List<String> Al = new ArrayList<>();
        Iterator<String> itr = testlist.iterator();
        while (itr.hasNext()) {
            item = itr.next();
            Al.add(item);
        }
        this.testlist = Al;
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Oracle");
        list.add("C++");
        DeepAndShollowCopy copy=new DeepAndShollowCopy(10,"Testing", list);
        System.out.println(copy.toString());
    }
    @Override
    public String toString() {
        return "DeepAndShollowCopy [id=" + id + ", name=" + name + ", testlist=" + testlist + "]";
    }
}

复制array:

Array是一个类,这意味着它是引用类型,因此array1 = array2的结果 在引用同一个数组的两个变量中。

但是看看这个例子:

  static void Main()
    {
        int[] arr1 = new int[] { 1, 2, 3, 4, 5 }; 
        int[] arr2 = new int[] { 6, 7, 8, 9, 0 };

        Console.WriteLine(arr1[2] + " " + arr2[2]);
        arr2 = arr1;
        Console.WriteLine(arr1[2] + " " + arr2[2]); 
        arr2 = (int[])arr1.Clone();
        arr1[2] = 12;
        Console.WriteLine(arr1[2] + " " + arr2[2]);
    }

浅克隆意味着只复制克隆数组所表示的内存。

如果数组包含值类型对象,则复制值;

如果数组包含引用类型,则只复制引用-因此有两个数组,其成员引用相同的对象。

要创建复制引用类型的深度复制,必须循环遍历数组并手动克隆每个元素。