Summary of replication methods for Java objects

Source: Internet
Author: User
Tags shallow copy

Reference: "Java Classic Programming" Example 054~058, "Java7 Primer Classic" 1. Using a constructor to copy an Object object is a call to a URL, and connecting directly through "=" does not achieve the purpose of copying the object. The following classes can replicate objects through constructors. The limitation is that the domain of the class that is required to generate the object is simply the base type and has no other reference type. If there are reference types, the new objects simply copy copies of the reference types, pointing to the same object, which is shallow copy. Unless the constructor is replicated again for that reference type, it is a deep copy until all the replications are for the base type.

According to the P250 page 6.8.3 section of the Java7 primer, the constructor method is a best practice for replicating object methods compared to complex clones of the second class.

First class: Fields have only basic types


Class II: The domain has a reference type addres address, and you need to copy it as well as the constructor
/** * Created: September 8, 2014 2:38:13 * Project name: Test * @author Cao Yanfeng * @since JDK 1.6.0_21 * Class Description: */public class E Mployee {private string name;private int age;private Address address;/** * Initialize */public Employee (String name,int Age,addre SS address) {//TODO auto-generated constructor stubthis.name=name;this.age=age;this.address=new address;} /** * Constructor Copy */public employee (employee employee) {//TODO auto-generated constructor Stubname=employee.getname (); age= Employee.getage (); Address=<span style= "font-family:arial, Helvetica, Sans-serif;" >new Address (</span><span style= "font-family:arial, Helvetica, Sans-serif;" >employee.getaddress () </span><span style= "font-family:arial, Helvetica, Sans-serif;" >) </span>;} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "Name:" +name+ ", Age:" +age+ ", Address--" +address;} Omit set () and get () function}/** * Created: September 8, 2014 2:52:18 project name: Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */publiC class Address {private string State;private string Province;private string city;/** * constructor implements replication */public address (address Address) {//TODO auto-generated constructor stubstate=address.state;province=address.province;city=address.city;} /** * Initialize */public Address (string state, String province, String city) {//TODO auto-generated constructor stubthis.state = State;this.province = Province;this.city = City;} @Overridepublic String toString () {//TODO auto-generated method Stubstringbuilder StringBuilder = new StringBuilder (); St Ringbuilder.append ("Country:" + state + ","); Stringbuilder.append ("Province:" + Province + ","); Stringbuilder.append ("City:" + cities); return stringbuilder.tostring ();}  Omit set () and get () function}
2. The effect of cloning objects and using constructors to replicate objects is highly consistent, limited by the fact that the domain that requires the class that generates the object is simply the base type and has no other reference type. If there is a reference type, the new object simply duplicates the copy of the reference type, pointing to the same object and not cloning it, which is a shallow clone. Unless you clone the reference type again until all clones are for the base type, this is the deep clone.
Note that all classes implement the Cloneable interface and override the Clone () method.
First class: Fields have only basic types
/
* * Created: September 8, 2014 2:38:13 project name: Test *  * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */public class Employee Imp Lements cloneable {private String name;private int age;/** * Initialize */public Employee (String name, int age) {//TODO Auto-gen erated constructor Stubthis.name = Name;this.age = age;} @Overrideprotected Employee Clone () throws Clonenotsupportedexception {//TODO auto-generated method Stubemployee Employee = Null;employee = (employee) super.clone (); return employee;} @Overridepublic String toString () {//TODO auto-generated method stub//return "name:" +name+ ", Age:" +age+ ", Address--" +address; Return "Name:" + name + ", Age:" + Ages;} Omit set () and get () function}


Class II: Domain has a reference type addres address, you need to clone it as well
/** * Created: September 8, 2014 2:38:13 project name: Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */public class Employee Imple ments cloneable {private String name;private int age; private Address address;/** * */public Employee (String name, int AG E,address Address) {//TODO auto-generated constructor stubthis.name = Name;this.age = age;this.address=address;} @Overrideprotected Employee Clone () throws Clonenotsupportedexception {//TODO auto-generated method Stubemployee Empl Oyee = Null;employee = (employee) super.clone (); Employee.address=address.clone (); return employee;} @Overridepublic String toString () {//TODO auto-generated Method Stub return "name:" +name+ ", Age:" +age+ ", Address--" +address;} Omit set () and get () function}/** * Created: September 8, 2014 2:52:18 project name: Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */public cl Address implements Cloneable{private string State;private string province;private string city;/** * Initialize */public addre SS (string state, String province, String city) {//TODO Auto-generated constructor stubthis.state = state;this.province = Province;this.city = City;} @Overrideprotected Address Clone () throws Clonenotsupportedexception {//TODO auto-generated method stubaddress address= null;address= (address) super.clone (); return address;} @Overridepublic String toString () {//TODO auto-generated method Stubstringbuilder StringBuilder = new StringBuilder (); St Ringbuilder.append ("Country:" + state + ","); Stringbuilder.append ("Province:" + Province + ","); Stringbuilder.append ("City:" + cities); return stringbuilder.tostring ();} Omit set () and get () function}
3. Serializing an object serializes the object to be copied from memory to a local file, and then reads from the local file into memory and assigns the new reference. The object sequence number implements deep cloning.
Note that the object to be serialized to implement the Serializable interface, if there is a reference type in the domain, also implement the Serializable interface, otherwise serialization error.
 /** * Created: September 8, 2014 2:36:34 * Project name: Test * @author Cao Yanfeng * @since JDK 1.6.0_21 * Class Description: */public class objectclonetest {/** * @param args * @throws clonenotsupportedexception */public static void Main (string[] args) throws C lonenotsupportedexception {//TODO auto-generated method stubaddress address=new address ("China", "Beijing", "Beijing"); Employee Employee=new Employee ("Cao Yanfong", 23,address); SYSTEM.OUT.PRINTLN (employee); Employee Employee2=null;objectoutputstream out=null;objectinputstream in=null;try {out=new ObjectOutputStream (new FileOutputStream ("Employee.dat")); Out.writeobject (employee); In=new ObjectInputStream (New FileInputStream (" Employee.dat ")); employee2= (Employee) In.readobject ();} catch (IOException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (ClassNotFoundException e) {//Todo A Uto-generated catch Blocke.printstacktrace ();}  System.out.println (EMPLOYEE2);}} /** * Created: September 8, 2014 2:38:13 project name: Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */public class Employee implements Serializable {/** * serial number */private static final long serialversionuid = 1l;private String name;private int age;private Address address;/** * */public Employee (String name, int age, address address) {//TODO Aut o-generated constructor stubthis.name = Name;this.age = Age;this.address = Address;} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "Name:" + name + ", Age:" + ages + ", address--" + addres s;} Omit set () and get () function}/** * Created: September 8, 2014 2:52:18 project name: Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 class Description: */public cl Address implements serializable{/** * Serial number */private static final long serialversionuid = 1l;private String State;priva Te string province;private string city;/** * Initialize */public Address (string state, String province, String city) {//TODO Aut o-generated constructor stubthis.state = state;this.province = Province;this.city = City;} @Overridepublic String toString () {//TODO auto-generated method Stubstringbuilder StringbuIlder = new StringBuilder () Stringbuilder.append ("Country:" + state + ","); Stringbuilder.append ("Province:" + Province + ","); stringb Uilder.append ("municipality:" + City); return stringbuilder.tostring ();} Omit set () and get () function}

Summary of replication methods for Java objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.