码迷,mamicode.com
首页 > 编程语言 > 详细

java的深拷贝和浅拷贝

时间:2014-10-31 00:01:20      阅读:404      评论:0      收藏:0      [点我收藏+]

标签:java深拷贝和浅拷贝

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实现的浅拷贝例子
		System.out.println(obj1);
		System.out.println(obj2);
		System.out.println("*****************");
		
		//序列化实现的深拷贝
		Test obj3=new Test(new User("hxh",24),168);
		ByteArrayOutputStream bout=new ByteArrayOutputStream();
		try {
			ObjectOutputStream obj=new ObjectOutputStream(bout);
			obj.writeObject(obj3);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.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 block
			e.printStackTrace();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
	}
}
bubuko.com,布布扣

java的深拷贝和浅拷贝

标签:java深拷贝和浅拷贝

原文地址:http://blog.csdn.net/cjc211322/article/details/40629785

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!