Reprint---Deep copy and normal copy of Java collection objects

Source: Internet
Author: User
Tags assert shallow copy

Original blog: http://blog.csdn.net/qq_29329775/article/details/49516247

There has been a recent error in doing algorithm jobs because there is no clear distinction between deep replication and shallow replication of Java collections.

1. First, the understanding of shallow copy and deep copy of the Java collection object

A normal collection copy simply copies the address of the in-memory stack so that a new collection object points to the address block, but the object variable in the collection points to the same area in the heap. So when the set of copies modifies the data within the collection object, the Source collection object is changed, which we call a shallow copy of the Java collection Object, which is simply copied in the stack, and the data in the heap is not copied. Deep replication is also a copy of the data in the stack and in the heap, so that the set of copies and the copied set have no relation.

2. An example

Create a new Demo class

1  Public classDemo {2           3     Private intDemovalue; 4           5      Public voidSetdemovalue (intvalue) {  6          This. Demovalue =value; 7     }  8           9      Public intGetdemovalue () {Ten         return  This. Demovalue;  One     }   A            -      PublicDemo () { -                the     }   -            -      PublicDemo (intdemovalue) {   -          This. Demovalue =Demovalue;  +     }   -}

Next, let's experiment with shallow replication:

1 @Test2  Public voidtestcommoncopy () {3   4     //Here I Create a source collection. 5Arraylist<demo> sourcecollection =NewArraylist<demo>(); 6   7     //Here I add some objects to sourcecollection. 8Sourcecollection.add (NewDemo (1)); 9Sourcecollection.add (NewDemo (2)); Ten    One     //Here I Create a new empty collection.  AArraylist<demo> newcollection =NewArraylist<demo>();  - Newcollection.addall (sourcecollection);  -    the     //Now I modify some objects in new collection.  -Newcollection.get (0). Setdemovalue (3);  -        -     //Now We Verify what it is inside the source collection.  +      for(Demo demo:sourcecollection) { - System.out.println (Demo.getdemovalue ());  +     }   A        at     //Now I Verify if the source Collection is modified.  -Assert.assertequals (Sourcecollection.get (0). Getdemovalue (), 1);  -}

As a result of its execution, it is clear that the changed demo object in Newcollection has changed in Sourcecollection, indicating that the demo object in both sets is the same object. This is also a shallow copy of the shortcomings of the existence. So how to separate two sets, that is, how to make a deep copy, we do not bother to continue to read:

First, let's Do the demo class, make it implement the Cloneable interface, and rewrite its clone method
1 protected throws clonenotsupportedexception {             2     return (Demo)Super. Clone ();   3 }

Then we'll do a deep copy:

1 @Test2  Public voidTestcopydeep ()throwsexception{3Arraylist<demo> sourcecollection =NewArraylist<demo>(); 4Sourcecollection.add (NewDemo (1)); 5Sourcecollection.add (NewDemo (2)); 6       7Arraylist<demo> newcollection =NewArraylist<demo>(); 8      for(Demo demo:sourcecollection) {9 Newcollection.add (Demo.clone ()); Ten     }   OneNewcollection.get (0). Setdemovalue (3);  A      for(Demo demo:sourcecollection) { - System.out.println (Demo.getdemovalue ());  -     }   theAssert.assertequals (Sourcecollection.get (0). Getdemovalue (), 1);  -}

Finally, let's take a look at the results: done.

Let's look at the reasons why this happens:

Deep copy: A with x1,x2,x3 ... Xn data, deep copy copies the data in each of its heaps and stacks, generating the corresponding y1,y2,y3 and B objects. At this point, a and B are stored separately in different address units, so the data in a is changed, the data in B is unchanged, and vice versa. Shallow copy: A is copied to B, but the data in a and b all point to the same x1,x2,x3 ... Xn, so when a changes the data by some means, for B, the data is changed.

Original blog: http://blog.csdn.net/qq_29329775/article/details/49516247

Reprint---Deep copy and normal copy of Java collection objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.