Deep copy and shallow copy of Java

Source: Internet
Author: User

Import Java.util.*;import Java.io.*;class user implements serializable{public String name;public int age;public User ( String str,int num) {name=str;age=num;} Public String toString () {return ' Name: ' +name+ ' \ n ' + ' Age: ' +age;}} Class Test implements Cloneable,serializable{public int height;public user user;public Test (user U,int num) {user=u; Height=num;} Public String toString () {return user+ "\ n" + "Height:" +height;} Public Object Clone () {try {return super.clone ();} catch (Clonenotsupportedexception e) {//TODO auto-generated catch block E.printstacktrace (); return null;}}} public class Arttracer{public static void Main (string[] args) {Test obj1=new Test (new User ("CJC", 25), 170); Test obj2= (Test) Obj1.clone (); obj1.user.age=30;//cloneable implementation of the shallow copy example System.out.println (OBJ1); System.out.println (OBJ2); System.out.println ("*****************");//serialization implementation of the deep copy test obj3=new test (new User ("Hxh", 24), 168); Bytearrayoutputstream bout=new Bytearrayoutputstream (); try {objectoutputstream obj=new ObjectOutputStream (bout); O Bj.writeobjECT (OBJ3);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} obj3.user.age=40;try {ObjectInputStream In=new ObjectInputStream (New Bytearrayinputstream (Bout.tobytearray ())); Test obj4= (Test) in.readobject (); System.out.println (OBJ3); System.out.println (OBJ4);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (ClassNotFoundException e) { E.printstacktrace ();}}}

Deep copy and shallow copy of Java

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.