ArrayListMain.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package samples.technology.reference;
  2. import java.util.ArrayList;
  3. import junit.framework.TestCase;
  4. class TestListClone implements Cloneable{
  5. public String intstr = "init value";
  6. public Test test = new Test();
  7. public void setStr(String str){
  8. intstr = str;
  9. }
  10. public Object clone(){
  11. TestListClone o = null;
  12. try{
  13. o = (TestListClone)super.clone();
  14. }catch(CloneNotSupportedException e){
  15. e.printStackTrace();
  16. }
  17. o.test = (Test)test.clone();
  18. return o;
  19. }
  20. }
  21. class Test implements Cloneable{
  22. public String teststr = "init test value";
  23. public Object clone(){
  24. Test o = null;
  25. try{
  26. o = (Test)super.clone();
  27. }catch(CloneNotSupportedException e){
  28. e.printStackTrace();
  29. }
  30. return o;
  31. }
  32. }
  33. public class ArrayListMain {
  34. public static void main(String[] a){
  35. ArrayList a1 = new ArrayList();
  36. TestListClone test = new TestListClone();
  37. a1.add(0,test);
  38. TestListClone test1 = (TestListClone)a1.get(0);
  39. System.out.println("before clone,a1= "+ test1.intstr);
  40. ArrayList a2 = new ArrayList();
  41. for(int i = 0; i < a1.size(); i ++){
  42. TestListClone test2 = (TestListClone) a1.get(i);
  43. TestListClone test3 = (TestListClone) test2.clone();
  44. a2.add(test3);
  45. }
  46. a2.add(1,"add value");
  47. System.out.println("=================================");
  48. System.out.println("after clone,a1.size = "+ a1.size());
  49. System.out.println("after clone,a2.size = "+ a2.size());
  50. TestListClone test2 = (TestListClone)a1.get(0);
  51. TestListClone test3 = (TestListClone)a2.get(0);
  52. //test3.setStr("change value");
  53. System.out.println("=================================");
  54. System.out.println("after clone,a1.size = "+ a1.size());
  55. System.out.println("after clone,a1 = "+ test2.toString());
  56. System.out.println("after clone,a2 = "+ test3.toString());
  57. System.out.println("after clone,a1 = "+ test2.test.toString());
  58. System.out.println("after clone,a2 = "+ test3.test.toString());
  59. }
  60. }