The Clone method does not simply use the Clone method in a Java cloned object, but only a shallow clone. Please look below:
Deep Clone classes:
Java code
Copy Code code as follows:
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
public class Depthclone {
Public final static Object Objectcopy (object oldobj) {
Object NEWOBJ = null;
try {
Bytearrayoutputstream bo = new Bytearrayoutputstream ();
ObjectOutputStream oo = new ObjectOutputStream (bo);
Oo.writeobject (oldobj);//Source Object
Bytearrayinputstream bi = new Bytearrayinputstream (Bo.tobytearray ());
ObjectInputStream oi= New ObjectInputStream (BI);
NEWOBJ = Oi.readobject ()//target object
catch (IOException e) {
E.printstacktrace ();
}catch (ClassNotFoundException e) {
E.printstacktrace ();
}
return NEWOBJ;
}
}
Shallow Clone class:
Java code
Copy Code code as follows:
Import java.io.Serializable;
public class Simpleclone implements Cloneable, Serializable {
Private static final long serialversionuid = -7552721152118950502l;
Public String s = null;
public Object o = null;
Public Cloneobject cloneobject = null;
Public Simpleclone (Cloneobject cloneobject) {
This.cloneobject = Cloneobject;
}
Public Object Clone () {
Simpleclone newsimpleclone = null;
try {
/* Shallow Clone/*
Newsimpleclone = (simpleclone) super.clone ();
catch (Clonenotsupportedexception e) {
E.printstacktrace ();
}
return newsimpleclone;
}
}
Clone object:
Java code
Copy Code code as follows:
Import java.io.Serializable;
public class Cloneobject implements serializable{
Private static final long serialversionuid = 4332788486669750696L;
private String name;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}
Cloning test:
Java code
Copy Code code as follows:
public class Testclone {
public static void Main (string[] arg) {
Cloneobject obj1 = new Cloneobject ();
Obj1.setname ("Cloneone");
Cloneobject obj2 = new Cloneobject ();
Obj2.setname ("Clonetwo");
Simpleclone simpleClone1 = new Simpleclone (OBJ1);
Simpleclone simpleClone2 = new Simpleclone (OBJ2);
SIMPLECLONE1.S = "SimpleClone1";
SIMPLECLONE1.O = "Simpleclone1object";
SimpleClone2 = (simpleclone) simpleclone1.clone ();
SimpleClone2 = (simpleclone) depthclone.objectcopy (SIMPLECLONE1);
/* If it is a shallow clone, the Cloneobject in the simpleClone1 will change with simpleClone2 cloneobject changes in the surface change * *
SimpleClone2.cloneObject.setName ("Clonethree");
System.out.println (SimpleClone1.cloneObject.getName ());
System.out.println (SimpleClone2.cloneObject.getName ());
}
}