Java Clone and JavaClone
For a common object, if you implement the Cloneable interface and override the clone method, you can implement deep copy of the object.
However, for a List or Set, both the clone method of the Set and the clone method of the object are shortest copies, that is, the pointer reference, to implement deep copy of a java set, you must implement the Serializable interface of the object and write a deep COPY method.
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. arrayList; import java. util. list; public class test {public static void main (String [] args) {List <Human> sdf = new ArrayList <Human> (); sdf. add (new Human ("sdf1", 100); sdf. add (new Human ("sdf2", 200); List <Human> h3c = null; try {h3c = deepCopy (sdf);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} Human h1 = h3c. get (0); h1.name = "h3c"; System. out. println (sdf. get (0 ). name + "-" + sdf. get (0 ). age); System. out. println (h3c. get (0 ). name + "-" + h3c. get (0 ). age);} static class Human implements Serializable {String name; int age; public Human (String n, int a) {this. name = n; this. age = a ;}// key code for deep copy public static <T> List <T> deepCopy (List <T> 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); @ SuppressWarnings ("unchecked") List <T> dest = (List <T>) in. readObject (); return dest ;}}
Java clone method
Import java. awt. Point;
// As follows
Public class Clone {
Public static void main (String [] args ){
// TODO Auto-generated method stub
Point p = new Point (4, 6 );
System. out. println (p );
// Completes a copy operation.
Point p1 = (Point) p. clone ();
System. out. println (p1 );
//
System. out. println (p = p1 );
// They are not the same object.
// This is the role of clone.
}
}
Java clone ()
This is the clone, clone, and copy method of the Object. After execution, the current Object is copied and returned.
The clone method class must implement the Cloneable interface first. Otherwise, the clone method will directly return an error that CloneNotSupportedException does not support cloning.
Therefore, the Employee must be implements Cloneable.
Because the clone method is available for objects, return (Employee) this. clone ();