例子
addAll()
- @Test
- public void CopyListTest(){
- Student student = Student.builder().id(1).name("张三").age(23).classId(1).build();
- Student student2 = Student.builder().id(2).name("李四").age(22).classId(1).build();
-
- List
students = new ArrayList<>(); - students.add(student);
- students.add(student2);
- System.out.println("旧的list");
- for (Student stu : students){
- System.out.println(stu);
- }
- List
list2 = new ArrayList<>(); - list2.addAll(students);
- list2.stream().forEach(t->t.setClassId(2));
- System.out.println("新的list");
- for (Student stu : list2){
- System.out.println("班级id"+stu.getClassId());
- }
- System.out.println("旧的list");
- for (Student stu : students){
- System.out.println("班级id"+stu.getClassId());
- }
- }
旧的list的值被改变
直接用 newList = oldList 是引用传递,复制的是地址
改变oldList里的内容同样也会影响到newListnewList.addAll(oldList)是值传递
但 用allAll() 原来的值也被改变了
解决
使用深度复制
- public static
List deepCopy(List sourceList) throws IOException, ClassNotFoundException{ - ByteArrayOutputStream bo= new ByteArrayOutputStream();
- ObjectOutputStream oos= new ObjectOutputStream(bo);
- oos.writeObject(sourceList);
- ByteArrayInputStream bi= new ByteArrayInputStream(bo.toByteArray());
- ObjectInputStream ois=new ObjectInputStream(bi);
- @SuppressWarnings("unchecked")
- List
dest = (List)ois.readObject(); - return dest;
- }
所复制的元素如果是对象,需要实现序列化。
如果所复制的元素是字符
List newList=new ArrayList(oldList);