Este artículo describe la función y el uso de replicación profunda de Java. Compártelo para su referencia, como sigue:
Escrito antes:
¿Qué es la replicación profunda? En Java, al crear un objeto, generalmente tenemos una referencia que apunta al objeto. Cuando cambiamos el valor (propiedades) del objeto refiriéndose a la variable, la referencia permanece sin cambios y cambia la memoria en la memoria, es decir, el objeto señaló. En términos generales, cuando asignamos esta referencia a otra variable de referencia o la pasamos como parámetro, solo la pasamos, es decir, apuntamos la referencia a "copiar" una copia a otra variable de referencia, y luego la variable de referencia también apunta al mismo objeto, y no se crea ningún objeto nuevo en la memoria. En algunos casos, necesitamos "realmente copiar" el objeto, crear una copia del objeto conocido, no solo "copiar" la referencia, ya sea una copia de seguridad u otras operaciones.
Entonces, ¿cómo lograrlo?
Hablemos primero sobre la idea: primero serializa el objeto en la transmisión, luego lo deserializamos y léelo de la transmisión.
El siguiente código:
paquete com.yo.java; import java.io.bytearrayInputStream; import java.io.bytearrayOutputStream; import java.io.ioException; import java.io.ObjectInputStream; import java.io.ObjectOutStreams java.util.list;/** * java implementa una copia profunda * @author yo * */public class DeepCopy implementa serializable {int i; / ** * @param args * @throws ioException * @throws classnotFoundException */ public static void main (string [] args) lanza ClassNotFoundException, ioException {Demo1 (); demo2 (); }/** * Copia profunda, la clase de parámetros real debe implementar la interfaz serializable * @param o * @return * @throws ioexception * @throws classnotFoundException */public static ojus oepeepcopy (object o) lanza byeException, classNotFoundException {// // Serialize primero y escriba a la transmisión de BytearRautput -boRAM byTeartArrayRAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUTAUT (new ByTearRAYAUT ObjectOutputStream oo = new ObjectOutputStream (bo); oo.writeObject (O); // luego deserializa y lee de la transmisión, es decir, copiar bytearrayInputStream bi = new ByteArrayInputStream (Bo.tobytearray ()); ObjectInputStream oi = new ObjectInputStream (BI); return oi.readObject (); } / ** * Paso de referencia y copia profunda * @throws classnotFoundException * @throws ioexception * / public static void demo1 () lanza ClassNotFoundException, ioException { System.out.println("========================================================================================== ============================================================================================================== ============================================================================================================== =======================================================================================================================================================================================================================================================================================. 1 ;/ Inicializar el valor de I en DC1 DeepCopy DC2 = DC1; System.out.println("===================================================================================== ========================================================================================================== ==================================================================================================================================================================================================================================================================================================. ========================================================================================================== (DeepCopy) DeepCopy (DC3); void demo2 () lanza ClassNotFoundException, ioException {System.out.println ("========================================================================================================= System. System. System. System. System. Out of System. System. Out of System. System. Out of System. System. Out of System. System. Out of System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. Out of System. System. System. System. Out of System. System. System. System. Out of System. System. System. System. Out of System. System. System. System. Out of System. System. System. System. Out of System. System. System. System. System. Out of System. System. System. System. System. System. Out of System. System. System. System. System. System. Out of System. System. System. System. System. System. System. System. Out of System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System. System src) The result is the same //Change the value of the element in list1 for(DeepCopy d1 : list1) { //Change the value of i in dc1 d1.i = 2; } // TransIP List para (DeepCopy D1: List1) {System.out.println ("List1:" + D1.i); System.out.println ("========================================================================== =================================================================================================================================================================================================================================================. =================================================================================================================================================================================================================================================. =================================================================================================================================================================================================================================================. New DeepCopy (); d3: list3) {system.out.println ("list3:" + d3.i);Los resultados de la operación anteriores son los siguientes (realmente medidos):
================================================================================================================== ================================================================================================================== ================================================================================================================== =========================================================================================================================================================================================== S : 2list4 (copia profunda): 1
Se puede ver que al referirse a pasar o crear un nuevo valor basado en el valor del objeto, solo se puede llamar "copia superficial". Cuando las propiedades del objeto original cambian, las propiedades del nuevo objeto creado de acuerdo con el método anterior también cambiarán en consecuencia; Y si se usa una copia profunda, es cierto que se copia un nuevo objeto. El nuevo objeto no tiene relación con el objeto original. El cambio de las propiedades del objeto original no afectará al nuevo objeto, al igual que el significado de la copia.
Como se mencionó anteriormente, si hay alguna inapropiado, si puede señalarlo, muchas gracias
Para obtener más contenido relacionado con Java, los lectores interesados en este sitio pueden ver los temas: "Estructura de datos de Java y tutorial de algoritmo", "Resumen de las puntas de nodo de operación de Java DOM", "Resumen de los archivos Java y consejos de operación de directorio" y "Summary of Java Cache Operation Tips" ".
Espero que este artículo sea útil para la programación Java de todos.