ArrayList<Person> list1 = new ArrayList<>(); Person p1 = new Person("lk1",90,23,178); Person p2 = new Person("lk2",91,24,190); list1.add(p1); list1.add(p2); List<Person> list2 = new ArrayList<>(list1); list2.get(0).setName("lk2"); System.out.println("list1:"+list1); System.out.println("list2:"+list2);
使用构造方法浅拷贝list1给list2,修改list2中的值会影响list1。
ArrayList<Person> list1 = new ArrayList<>(); Person p1 = new Person("lk1",90,23,178); Person p2 = new Person("lk2",91,24,190); Person p3 = new Person("lk3",91,24,190); list1.add(p1); list1.add(p2); List<Person> list2 = new ArrayList<>(list1); list2.add(p3); System.out.println("list1:"+list1); System.out.println("list2:"+list2);
list2添加元素为啥不影响list1呢