java 集合类型的clone

前一篇写到java中深层拷贝(Deep Copy)和浅层拷贝(Shadow Copy)。http://blog.csdn.net/jazywoo123/article/details/8000185

由于集合本身就是采用引用的方式保存元素的,所以集合.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


你可能感兴趣的:(java,exception,String,Class,import)