package samples.technology.reference; import java.util.ArrayList; import junit.framework.TestCase; class TestListClone implements Cloneable{ public String intstr = "init value"; public Test test = new Test(); public void setStr(String str){ intstr = str; } public Object clone(){ TestListClone o = null; try{ o = (TestListClone)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } o.test = (Test)test.clone(); return o; } } class Test implements Cloneable{ public String teststr = "init test value"; public Object clone(){ Test o = null; try{ o = (Test)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return o; } } public class ArrayListMain { public static void main(String[] a){ ArrayList a1 = new ArrayList(); TestListClone test = new TestListClone(); a1.add(0,test); TestListClone test1 = (TestListClone)a1.get(0); System.out.println("before clone,a1= "+ test1.intstr); ArrayList a2 = new ArrayList(); for(int i = 0; i < a1.size(); i ++){ TestListClone test2 = (TestListClone) a1.get(i); TestListClone test3 = (TestListClone) test2.clone(); a2.add(test3); } a2.add(1,"add value"); System.out.println("================================="); System.out.println("after clone,a1.size = "+ a1.size()); System.out.println("after clone,a2.size = "+ a2.size()); TestListClone test2 = (TestListClone)a1.get(0); TestListClone test3 = (TestListClone)a2.get(0); //test3.setStr("change value"); System.out.println("================================="); System.out.println("after clone,a1.size = "+ a1.size()); System.out.println("after clone,a1 = "+ test2.toString()); System.out.println("after clone,a2 = "+ test3.toString()); System.out.println("after clone,a1 = "+ test2.test.toString()); System.out.println("after clone,a2 = "+ test3.test.toString()); } }