Deep copy of Java List

Source: Internet
Author: User
Tags object serialization

The problem of deep copy and shallow copy is always encountered, here are some tests, the code is as follows:

/* To change this template, choose Tools | Templates * and open the template in the editor. */import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.IOException;import Java.io.objectinputstream;import java.io.objectoutputstream;import Java.io.serializable;import java.util.*;/** * * @  Author User */class Weiz implements serializable{private static final long serialversionuid=123l;  Double X;  Public Weiz (double a) {x=a; }}public class Test_copy {/** * @param args the command line arguments */public static void main (string[] args) throws IOException, ClassNotFoundException {//TODO code application logic here list<weiz> lst=        New ArrayList ();        Lst.add (New Weiz (1.1));        Lst.add (new Weiz (1.2));        Lst.add (New Weiz (1.3));        System.out.println ("Before copying:");        for (int i=0;i<lst.size (); ++i) {System.out.println (Lst.get (i) + "" +lst.get (i). x);        }//system.out.println (); //The constructor copies a shallow copy of the list<weiz> lst2=new ArrayList (LST);        Lst2.set (1, New Weiz (2.1));        Lst2.get (0). x=2.1;        System.out.println ("The constructor is copied and modified, the new lst2:");        for (int i=0;i<lst2.size (); ++i) {System.out.println (Lst2.get (i) + "" +lst2.get (i). x);        } System.out.println ("Original lst:" After the constructor is copied and modified);        for (int i=0;i<lst.size (); ++i) {System.out.println (Lst.get (i) + "" +lst.get (i). x);        } list<weiz> lst3=deepcopy (LST);        Lst3.get (0). x=3.1;        System.out.println ("Object serialized copy and modified, new lst3:");        for (int i=0;i<lst3.size (); ++i) {System.out.println (Lst3.get (i) + "" +lst3.get (i). x);        } System.out.println ("Object serialized copy and modified, original LST:");        for (int i=0;i<lst.size (); ++i) {System.out.println (Lst.get (i) + "" +lst.get (i). x);        } list<weiz> lst4=deepcopy (LST);        Lst4.get (0). x=4.1;        System.out.println ("Object serialized copy and modified, new lst4:"); for (int i=0;i<lst4.size (); ++i) {System.out.println (Lst4.get (i) + "" +lst4.get (i). x);        } System.out.println ("Object serialized copy and modified, original LST:");        for (int i=0;i<lst.size (); ++i) {System.out.println (Lst.get (i) + "" +lst.get (i). x); }}//Critical code performs serialization and deserialization for deep copy public static <T> list<t> deepcopy (list<t> src) throws Ioex          Ception, classnotfoundexception {bytearrayoutputstream byteout = new Bytearrayoutputstream ();          ObjectOutputStream out = new ObjectOutputStream (byteout);            Out.writeobject (SRC);          Bytearrayinputstream Bytein = new Bytearrayinputstream (Byteout.tobytearray ());          ObjectInputStream in = new ObjectInputStream (Bytein);          @SuppressWarnings ("unchecked") list<t> Dest = (list<t>) in.readobject ();      return dest;      }//Key code performs serialization and deserialization for deep copy, different writing, the same function//personal habits how to like how to come! Public list deepCopy2 (list src) throws IOException, CLASSNOTFoundexception{Bytearrayoutputstream byteout = new Bytearrayoutputstream ();                     ObjectOutputStream out = new ObjectOutputStream (byteout);                            Out.writeobject (SRC);                     Bytearrayinputstream Bytein = new Bytearrayinputstream (Byteout.tobytearray ());                     ObjectInputStream in =new ObjectInputStream (Bytein);                     List dest = (list) in.readobject ();             return dest; }   }

The results of the operation are as follows:

Run: Pre-copy: [email protected] 1.1[email protected] 1.2[email protected] 1.3 constructor copied and modified, new Lst2:[email protected] 2.1[email Protected] 1.2[email protected] 1.3 constructor copied and modified, original Lst:[email protected] 2.1[email protected] 1.2[email protected] 1.3 After the object is serialized and modified, the new Lst3:[email protected] 3.1[email protected] 1.2[email protected] 1.3 object is serialized and modified, the original Lst:[email Protected] 2.1[email protected] 1.2[email protected] 1.3 object serialized copy and modified, new Lst4:[email protected] 4.1[email protected] 1.2[ Email protected] 1.3 object serialized copy and modified, original Lst:[email protected] 2.1[email protected] 1.2[email protected] 1.3

As you can see, the method of using the constructor (the old list) is a shallow copy, copying only the elements in the list, that is, the references, not the values that these elements or references point to.

The object serialization method is a deep copy, which re-creates a copy of the object to which the references are directed.

From the printed results can also be seen, shallow copy, the value of the element in the new list is the same as the old list, that is, the reference is the same, while the deep copy, the value of the element in the new list is not the same as the old list, that is, the reference value is not the same, you think, deep copy is re- Then the reference value pointing to the new object is certainly not the same as the old one!


The object serialization method is to refer to other articles, which are linked here.

When the class implements the Serializable interface, its object is serializable. In fact, Serializable is an empty interface whose purpose is simply to identify an object of a class that can be serialized.

The Serialversionuid attribute in a serializable class is used to identify the serialized version of the class, and if the attribute is not displayed, the JVM calculates its value based on the information about the class, and the result of the class modification is often different from the result of the modification, so that the deserialization fails because of incompatible versions.

If a class is serializable, all its subclasses are also serializable. When serializing an object, if the object's properties refer to other objects, the referenced object must also be serializable.

Deep copy of Java List

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.