- 当list = list的时候,仅仅是地址的复制,如果修改其中一个list必定改变另外一个list
- 当list.addall(list)的时候,只是一个浅复制,如果只是remove,和1不同的是另一个list不会改变(对于基本类型而言),当类型是类的话,如果对象的属性改变了,另一个list也会改变
List<List>
类型的用add方法时,如果<>
里面的List改变了就会导致List<List>
改变
public static void main(String[] args){
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
List<Integer> integerList1 = new ArrayList<>();
integerList1 = integerList;
integerList.remove(0);
System.out.println("integerList:"+integerList);
System.out.println("integerList1:"+integerList1);
//integerList:[2, 3]
//integerList1:[2, 3]
List<Integer> integerList2 = new ArrayList<>();
integerList2.addAll(integerList);
integerList.remove(0);
System.out.println("integerList:"+integerList);
System.out.println("integerList2"+integerList2);
//integerList:[3]
//integerList2[2, 3]
List<ListNode> listNodes = new ArrayList<>();
listNodes.add(new ListNode(1));
listNodes.add(new ListNode(2));
listNodes.add(new ListNode(3));
List<ListNode> listNodes1 = new ArrayList<>();
listNodes1.addAll(listNodes);
listNodes.get(0).setVal(4);
System.out.println("listNodes:"+listNodes);
System.out.println("listNodes1:"+listNodes1);
//listNodes:[ListNode{val=4, next=null}, ListNode{val=2, next=null}, ListNode{val=3, next=null}]
//listNodes1:[ListNode{val=4, next=null}, ListNode{val=2, next=null}, ListNode{val=3, next=null}]
listNodes.remove(0);
System.out.println("listNodes:"+listNodes);
System.out.println("listNodes1:"+listNodes1);
//listNodes:[ListNode{val=2, next=null}, ListNode{val=3, next=null}]
//listNodes1:[ListNode{val=4, next=null}, ListNode{val=2, next=null}, ListNode{val=3, next=null}]
List<List<Integer>> lists = new ArrayList<>();
lists.add(integerList);
System.out.println("lists:"+lists);
System.out.println("integerList:"+integerList);
//lists:[[3]]
//integerList:[3]
integerList.clear();
System.out.println("lists:"+lists);
System.out.println("integerList:"+integerList);
//lists:[[]]
//integerList:[]
}