浅层复制代码:
1 import java.util.*; 2 3 class Int{ 4 private int i; 5 public Int(int ii){i = ii;} 6 public void increment(){i++;} 7 public String toString(){ 8 return Integer.toString(i); 9 } 10 } 11 12 public class Cloning{ 13 public static void main(String[] args){ 14 Vector v = new Vector(); 15 for(int i = 0; i < 10; i++) 16 v.addElement(new Int(i)); 17 System.out.println("v: "+v); 18 Vector v2 = (Vector)v.clone(); 19 for(Enumeration e = v2.elements();e.hasMoreElements();) 20 ((Int)e.nextElement()).increment(); 21 System.out.println("v: "+v); 22 } 23 }
输出:
v: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] v: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
分析:
Java中的引用指向原来的对象,任何的修改操作会引起原来对象的修改
原文:http://www.cnblogs.com/hu983/p/5419118.html