集合的clone

之前看《高质量Java程序设计》,看到有关集合的深层拷贝(Deep Copy)和浅层拷贝(Shadow Copy)。今天试了一下。

由于集合本身就是采用引用的方式保存元素的,所以集合.clone()产生的对象其对元素的保存方式也是引用。比如,ArrayList类对象ar 中有元素student1, student2(的引用),现在copy  = ar.clone().那么copy中所保存的也只是student1 和student2 的引用。

这说明,使用集合的clone功能,并不是获得我们所想象的如同一般对象那样获得非引用的拷贝。要实现集合的拷贝,必须新建一个集合,然后将原集合中元素的clone逐一加到新的集合中。如示例程序:

//浅层拷贝

import java.util.*;
public class ShadowCopy { 

 public static void main(String[] args) throws Exception{
  Student st1 = new Student(1, "no1");
  Student st2 = new Student(2, "no2");
  
  ArrayList ar = new ArrayList();
  ar.add(st1);
  ar.add(st2);
  
  ArrayList copy = (ArrayList)ar.clone(); //直接使用集合的clone功能
  ((Student)copy.get(1)).setStudent(222, "   no22");//由结果可以看到,这里对copy的修改影响了ar。
  
  System.out.println((Student)ar.get(1));
  System.out.println((Student)copy.get(1));
 } 
}
输出:

222   no22

 

//深层拷贝

import java.util.*;
public class DeepCopy { 

 public static void main(String[] args)  throws Exception{
  Student st1 = new Student(1, "no1");
  Student st2 = new Student(2, "no2");
  
  ArrayList ar = new ArrayList();
  ar.add(st1);
  ar.add(st2);
  
  ArrayList copy = new ArrayList(); //这里演示Deep Copy的方法
  copy.add(st1.clone());
  copy.add(st2.clone());
  
  
  ((Student)copy.get(1)).setStudent(222, "   no22"); //这样,对copy的修改不会影响ar。
  
  System.out.println((Student)ar.get(1));
  System.out.println((Student)copy.get(1));
 } 
}
输出:

2no2
222   no22

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值