Deep replenishment and shallow copy

xiaoxiao2021-03-06  39

In the process of programming, it is inevitable that you need a copy of the program, that is, I need this object and to change the existing state of the object but want to retain the status of the original object. At this time, we will use the copy of the object, of course, this situation exists only in the object. We can declare a copy of the object to INT, FLOAT.DOUBLE and STRING in the object. But for true objects, use = operationally active reference, that is, the pointing between the two ends is the same memory address, so any one of the operations will change. In this case we can use the cloning method. That is, Clone () method allows you to get a copy of an object. It is also necessary to pay the corresponding price to implement the clonable interface. Then implement the method of this excuse clone () so you can get a copy of the object you want to get. Such as: class TestClone implements Clonalbe {private String filed1; private String filed2; public TestClone (String name1, String name2) {filed1 = name1; filed2 = name2;} public Object clone () {TestClone temp = null; try {temp = ( TestClone) Super.clone ();} catch (clonenotsupportexception e) {system.out.println ("clone fail");} return temp;}}}, but this method can only clon the basic type if the object's properties There is also an object, you need to be implemented in the Clone method, this is more troublesome, because we don't know how many objects do you have on such an iteration, how much processing is to do. The new method is to use the serialization method. The serialization process is actually serializing the object's copy so that we can simply serialize an object and then go out, it can be cloned, and All of the content inside is cloned. The serialization process needs to implement a serializable interface to support serialization. For example: Class TestSerial implements Serializable {private TestClone cloneObject = new TestClone ( "1", "3"); private String test = "343434"; public static void main (String [] args) {TestSerial t1 = new TestSerial (); ByteArrayOutputStream bo = new ByteArrayOutputStream (); ObjectOutputStream objectOut = new ObjectOutputStream (bo); objectOut.writeObject (t1); ObjectIutputStream in = new ObjectInputStream (new ByteArrayInputStream (bo.toByteArray ())); TestSerial t2 = (TestSerial) in.readObject ();}} If you want a class with deep copy, you can write a method to modify the code in the above. Clone is just copying the basic element so it is shallow copy, and the use of the Serializable interface can be fully replicated. The above is a brief introduction to deep reprint and shallow resend, I hope to help everyone.

转载请注明原文地址:https://www.9cbs.com/read-75122.html

New Post(0)