Java的深度复制与浅层复制(二)
编程技术  /  houtizong 发布于 3年前   62
1. public class Student implements Serializable { 2. 3. private String name; 4. private String tel; 5. private int age; 6. 7. //set and get..... 8. } 9. 10. public class Teacher implements Serializable { 11. 12. private String name; 13. private int age; 14. private List<Student> stuList; 15. 16. //set and get.... 17. 18. } 19. 20. import java.io.ByteArrayInputStream; 21. import java.io.ByteArrayOutputStream; 22. import java.io.IOException; 23. import java.io.ObjectInputStream; 24. import java.io.ObjectOutputStream; 25. import java.util.ArrayList; 26. import java.util.List; 27. 28. public class Test { 29. 30. 31. public static void main(String[] args) { 32. Student s1 = new Student(); 33. s1.setName("Wang"); 34. s1.setAge(25); 35. s1.setTel("110"); 36. Student s2 = new Student(); 37. s2.setName("Li"); 38. s2.setAge(35); 39. s2.setTel("119"); 40. 41. 42. Teacher t = new Teacher(); 43. t.setName("Zhang"); 44. t.setAge(50); 45. List<Student> stuList = new ArrayList<Student>(); 46. stuList.add(s1); 47. stuList.add(s2); 48. t.setStuList(stuList); 49. System.out.println("t: "+t); 50. System.out.println("s1: "+s1); 51. System.out.println("s2: "+s2); 52. System.out.println("after clone--------------"); 53. Teacher t2 = (Teacher) depthClone(t); 54. System.out.println("t2: "+t2); 55. System.out.println("t: "+t); 56. 57. Student s3 = t2.getStuList().get(0); 58. Student s4 = t2.getStuList().get(1); 59. System.out.println("s3: "+s3); 60. System.out.println("s1: "+s1); 61. System.out.println("s4: "+s4); 62. System.out.println("s2: "+s2); 63. 64. System.out.println("after change--------------"); 65. t2.setAge(55); 66. t2.setName("Zhao"); 67. 68. System.out.println("t2 Name: "+t2.getName()+" t2 age"+t2.getAge()); 69. System.out.println("t Name: "+t.getName()+" t age"+t.getAge()); 70. 71. } 72. 73. private static Object depthClone(Object srcObj){ 74. Object cloneObj = null; 75. try { 76. ByteArrayOutputStream out = new ByteArrayOutputStream(); 77. ObjectOutputStream oo = new ObjectOutputStream(out); 78. oo.writeObject(srcObj); 79. 80. ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); 81. ObjectInputStream oi = new ObjectInputStream(in); 82. cloneObj = oi.readObject(); 83. } catch (IOException e) { 84. e.printStackTrace(); 85. } catch (ClassNotFoundException e) { 86. e.printStackTrace(); 87. } 88. return cloneObj; 89. } 90. 91. }
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接