Java depth Copy

Source: Internet
Author: User

Reprint: http://atjava.iteye.com/blog/1722501

First, let's look at the definition of shallow copy and deep copy

Shallow copy : Only one object is copied, an array of objects that exist inside the object, or references are not copied
deep copy : Objects, references within objects are copied
To better understand their differences we assume that there is an object A, which contains 2 objects, objects A1 and objects A2
Object A has a shallow copy of object B, but the object A1 and A2 are not copied.
Object A makes a deep copy, and the A1 and A2, along with their references, are also copied when the object B is obtained.
After understanding deep and shallow copies, let's look at the deep copy and shallow copy implementations of Java.

The Clone method of the Object class performs a specific clone operation.
First, if the class of this object cannot implement interface cloneable, then Clonenotsupportedexception will be thrown. (Note: All arrays are considered to implement Interface Cloneable)
This method creates a new instance of the class for this object, and initializes all fields of the object, as it is assigned, using the contents of the corresponding field of this object strictly, and the contents of these fields are not self-cloned. Therefore, this method performs a "shallow copy" of the object, not a "deep copy" operation.
The object class itself does not implement interface cloneable, so calling the Clone method on an object that is class object will cause an exception to be thrown at run time.

Here's a look at the difference between the three copied instance codes, and we need to build the person class:

Java code
  1. Public class person{
  2. private String name;
  3. private int age;
  4. Public person (String name, int age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. public void Setage (int.) {
  9. this.age = age;
  10. }
  11. public void SetName (String name) {
  12. this.name = name;
  13. }
  14. public void display () {
  15. System.out.println ("Name:" + name + "/tage:" + age);
  16. }
  17. }



I. GENERAL replication
That's the easiest thing to think about is assigning an object to another object.

Java code
  1. Public static void Main (string[] args) {
  2. Person p1=New person ("Jack",20);
  3. Person P2=P1;
  4. P1.setage (); Simple Replication
  5. P2.display ();
  6. P1.display ();
  7. System.out.println (p1);
  8. System.out.println (p2);
  9. }



Results: Name:jack age:49
Name:jack age:49
[Email protected]
[Email protected]
Note that the P1 and P2 objects are the same reference, so changing the property 2 is a change.

Second, shallow copy
A clone method to implement the Cloneable interface of the book class by a shallow copy

Java code
  1. Public class book implements cloneable{
  2. String BookName;
  3. double Price;
  4. person author;
  5. Public book (String bn,double Price,person author) {
  6. BookName = bn;
  7. this.price = Price;
  8. This.author = author;
  9. }
  10. Public Object Clone () {
  11. Book B = null;
  12. try{
  13. b = (book)Super.clone ();
  14. }catch (Clonenotsupportedexceptione) {
  15. E.printstacktrace ();
  16. }
  17. return B;
  18. }
  19. public void display () {
  20. System.out.print (BookName + "/t" +price + "/t");
  21. Author.display ();
  22. }
  23. }
  24. Publicstatic void Main (stringargs[]) {
  25. Book B1 = new book ("Java Programming",30.50,new Person ("Zhang San",34));
  26. Book b2 = (book) b1.clone ();
  27. B2.price = 44.0;
  28. B2.author.setAge (45);
  29. B2.author.setName ("John Doe");
  30. B2.bookname = "Java development";
  31. B1.display ();
  32. B2.display ();
  33. }



Results:
Java programming 30.5 Name: John Doe age:45
Java Development 44.0 Name: John Doe age:45
Note that B1 and B2 are different objects, but B1.author and B2.author point to the same object.

The problem is as follows: Discovering that the properties of the author object B1 when changing B2 's author object properties have also changed, stating that the author object in a shallow copy is not completely copied, but uses the same reference, so that a deep copy is used.

Third, deep copy
In order to solve the above problem, we need to use a deep copy, in fact, it is very simple to copy the book object when adding the following statement

Java code
    1. B.author = (person) author.clone (); //Copy the person object, the person object needs to be copied

Running the main method above, the result is as follows:
Java programming 30.5 Name: Zhang San age:34
Java Development 44.0 Name: John Doe age:45
Description B1 and B2 are different objects, b1.author and B2.author point to different objects. (contains a copy of the property of the referenced object).

The Clone () method of the JAVA.LANG.T default is to return a pre-copied object. So if you want to implement a deep copy using the Clone () method, we must implement the Clone () method for each object specifically. When the object hierarchy is complex, this is not only difficult and time-consuming and error prone, especially when you need a deep copy and you also have a shallow copy of the object, you will find that writing this clone () method is really not a good solution.

So what can we do with the addition of the Clone () method? The answer is serialization .
The serialized object implements the serializable interface for serialization, and the object's member object is also serialized.

Java code
    1. a a=new a ();   
    2. //write object, serialize     
    3.  bytearrayoutputstream byteout  = new bytearrayoutputstream ();    
    4.   Objectoutputstream out= new objectoutputstream (byteout);    
    5.  out.writeobject (a);   
    6.  //read object, deserialization    
    7.   ByteArrayInputStream byteIn =  new bytearrayinputstream (Byteout.tobytearray ());   
    8.  a b= (A) in.readobject ();   


Serialization is often used for file-pass reads. In particular, it is used more in the cache, and the object can be cached on the hard disk by serialization. This is most common when logging on to the system to cache user rights and roles. It's also a good way to clone objects.


The Clone method of the Java.lang.Object class is a protected method in which the subclass needs to override this method and declare it as a public type, and also implement the Cloneable interface to provide the ability to copy objects, Clone () is a native method , the efficiency of the native method is generally much higher than the non-native method in Java, which is more concerned with performance, the other way--copying objects through the reflection mechanism of Java, which can be less efficient than clone (). Deep copying and copying collection types are not supported, but versatility is much higher, and the following is the code for replication:

Java code
  1. Private <T> t Getbean (t Targetbean, T Sourcebean) {
  2. if (targetbean== null) return null;
  3. field[] Tfields = Targetbean.getclass (). Getdeclaredfields ();
  4. field[] Sfields = Sourcebean.getclass (). Getdeclaredfields ();
  5. try {
  6. For (Field field:tfields) {
  7. String fieldName = Field.getname ();
  8. if (fieldname.equals ("Serialversionuid")) continue;
  9. if (field.gettype () = = Map.   Class) continue;
  10. if (field.gettype () = = Set.   Class) continue;
  11. if (field.gettype () = = List.   Class) continue;
  12. For (Field sfield:sfields) {
  13. if (!sfield. GetName (). Equals (FieldName)) {
  14. continue;
  15. }
  16. Class type = Field.gettype ();
  17. String setName = Getsetmethodname (fieldName);
  18. Method TMethod = Targetbean.getclass (). GetMethod (SetName, new Class[]{type});
  19. String getName = Getgetmethodname (fieldName);
  20. Method Smethod = Sourcebean.getclass (). GetMethod (GetName, null);
  21. Object Settervalue = Vomethod.invoke (Sourcebean, null);
  22. Tmethod.invoke (Targetbean, new Object[]{settervalue});
  23. }
  24. }
  25. } catch (Exception e) {
  26. throw New Exception ("error setting parameter information", e);
  27. }
  28. return Targetbean;
  29. }

The method receives two parameters, one is the copy of the source object-the object to be copied, one copy of the target object-the object copy, of course, this method can also be used between two different objects, as long as the target object and object has one or more properties of the same type and name, The property value of the source object is then assigned to the property of the target object.

Java depth Copy

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.