Detailed explanation of shallow cloning and deep cloning of objects in Java
This article mainly introduces the relevant information about the cloning of java objects. Here is an example analysis of shallow cloning and deep cloning. Friends who need it can refer to it
Clone of java objects
1. Shallow cloning of objects
(1) If you need to clone a class, you need to override the clone method of the Object class and implement the Cloneable interface (identification interface, no need to implement any Method)
(2) When the object that needs to be cloned maintains another reference object, shallow cloning will not clone the other reference object, but directly copy the address of the other reference object maintained.
(3) Shallow cloning of objects will not call the constructor.
The following is an example of shallow cloning of an object:
package com.clone; import java.io.Serializable; /** * Description: * 实现了Cloneable接口,并重写Object类的clone方法。 * * @author lee * */ public class CloneDemo1 implements Cloneable,Serializable{ //该克隆类封装的信息 public int id; public String name; public Address address; /** * Desciption: * 默认构造器 * * */ public CloneDemo1(){} /** * Description: * 初始化id,name的构造器 * * @param id id * @param name 名字 * @param address 地址 * */ public CloneDemo1(int id, String name, Address address){ this.id=id; this.name=name; this.address = address; } /** * Descriptin: * 重写Object类的clone方法。 * if the object's class does not support the Cloneable interface. * Subclasses that override the clone method can also throw this exception * to indicate that an instance cannot be cloned. * * @throws CloneNotSupportedException * */ @Override public Object clone() throws CloneNotSupportedException{ return super.clone(); } /** * Description: * 重写toString方法 * * @return "id="+id+", name="+name * */ @Override public String toString(){ return "id="+id+", name="+name+", address:"+address.getAddress(); } /** * Description: * 主方法 * * */ public static void main(String[] args) throws CloneNotSupportedException{ CloneDemo1 c1 = new CloneDemo1(1,"c1",new Address("北京")); //c2 复制了c1的地址,并没有复制整个c1对象 CloneDemo1 c2 = c1; //c3 对象的浅克隆,复制了整个对象 CloneDemo1 c3 = (CloneDemo1)c1.clone(); //当对象c1改变其name或者id的时候,c2也会自动改变。 //因为c2只是复制了c1的地址,并非复制了c1的整个对象。 //相应的c3则不会随着c1改变而改变,意味着c3将c1整个对象克隆一份出来。 //当是,对象的浅克隆不会克隆被克隆对象当中的引用对象。 //因此c1改变其中的Address的引用对象时,c2,c3也会跟着改变。 c1.setName("cc"); c1.address.setAddress("上海"); System.out.println(c1+"\n"+c2+"\n"+c3); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } /** * Description: * 一个封装着地址的类 * * @author lee * */ class Address implements Serializable{ public String address; /** * Description: * 默认构造器 * * */ public Address(){} /** * Description: * 初试化address * * @param address 地址 * */ public Address(String address){ this.address = address; } //address的set和get方法 public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
2. Deep cloning of an object
Is to use the input and output stream of the object to write the object to the file, and then read the object information. This is the deep cloning of the object.
Because shallow cloning of an object does not clone the reference object in the cloned object, but directly copies its address. Therefore, cloning a reference type in the cloned object requires deep cloning of the object.
The deep cloning of an object uses object serialization input and output.
The code is as follows:
package com.clone; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Description: * 实现对象的深克隆 * * @author lee * */ public class CloneDemo2 { /** * Description: * 将对象输出到一个文件当中。 * * @param c 需要被写到文件当中的对象。 * */ public static void writeObject(CloneDemo1 c){ ObjectOutputStream out = null; try{ //将对象输出在一个object.txt文件当中 out = new ObjectOutputStream(new FileOutputStream("./object.txt")); out.writeObject(c); }catch(IOException e){ System.out.println("写入对象的时候发生了错误。"); e.printStackTrace(); }finally{ //关闭资源 try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } } /** * Description: * 从文件中读取出一个对象来,并返回。 * * @return c 返回一个对象。 * */ public static CloneDemo1 readObject(){ CloneDemo1 c = null; ObjectInputStream input = null; try{ //从object.txt文件中读取一个对象出来 input = new ObjectInputStream(new FileInputStream("./object.txt")); c = (CloneDemo1)input.readObject(); }catch(IOException | ClassNotFoundException e){ e.printStackTrace(); System.out.println("读取对象的时候发生了错误。"); }finally{ //关闭资源 try{ input.close(); }catch(IOException e){ e.printStackTrace(); } } return c; } /** * Description: * 主方法 * * @throws CloneNotSupportedException * */ public static void main(String[] args) throws CloneNotSupportedException { CloneDemo1 c1 = new CloneDemo1(1,"c1",new Address("北京")); //c2 对象的浅克隆 CloneDemo1 c2 = (CloneDemo1)c1.clone(); //c3对象的深克隆 writeObject(c1); CloneDemo1 c3 = readObject(); //因为对象的深克隆同时也克隆了被克隆对象维护的另外一个对象 //所以,当c1改变其当中的维护的另外一个对象的时候,c3不会随之改变。 //而c2位浅克隆,其维护的另外一个对象只是复制了c1维护的对象的地址,因此会随着c1的改变而改变。 c1.address.setAddress("上海"); System.out.println(c1+"\n"+c2+"\n"+c3); } }
The serialization of objects requires the implementation of the Serializable interface.
The above is the detailed content of Detailed explanation of shallow cloning and deep cloning of objects in Java. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools
