当前位置:编程学习 > JAVA >>

java中对象的值引用和值拷贝 以及对象的深克隆,浅克隆

今天忽然用到了最基础的java中的值引用和值拷贝,以及对象的浅克隆和深克隆,别那么绕圈子了,直接上例子
简单类型值引用、也属于值cope;
 int a=3
int b=a
那么不管a再怎么改变值,b的值不会因为a的改变再改变了,但是如下例:
Student{
String name;
int sex;
}
Student  stu1=new Student ();
Student  stu2=stu1;
stu1.setName("1122');
这个属于对象的赋值,但是只是对象的引用。
此时stu2中的name也是改变为了1122
如果不想受影响可以采用下面的方法

Student  stu2=stu1;
换为
Student  stu2=null;
Beanutils.copePorperties(stu1,stu2);//此处的beanutils 为spring中的类
此种赋值也称为浅克隆
 
如果Sturdent这个类中有对象的引用,使用上面的方法也不能解决对象中的属性被改变,这时候就需要用到深克隆
举个例子:
 
class Student{
String name;
int sex;
public List<Person> li;
}
如果你需要改变Student‘中的属性li里面Person对象中的值,而使其他备份不受影响则需要使用以下方法
1 Student这个类要实现序列话接口
2 加入一个克隆方法
修改后代码如下:
class Student implements Serializable{
String name;
int sex;
public List<Person> li;
public Student deepClone() {
 Studentdc = null;
    try {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(this);
  oos.close();
 
  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream bis = new ObjectInputStream(bais);
  dc = (Student)bis.readObject();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (ClassNotFoundException e) {
  e.printStackTrace();
 }
    return dc;
}
使用时候只需要如下进行操作即可:
Student stu1=new Student();
stu2=stu1.deepClone();
 
再进行改变stu1中的任何值,也不会影响stu2中的值了。
特别注意,Person类也要实现序列化接口,否则在序列化Student时会抛出异常。
}
 
 
 
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,