輸出不言自明。
誤解
1)temp.remove(temp.size() - 1);
這從temp list
刪除最後一個元素,並且自temp list
被稱爲內部result
所以得到引用那裏。
2.)temp.add(1, 3);
它將在temp list
索引1在添加值3。
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
temp.add(1);
temp.add(2);
System.out.println("Temp is : " + temp);
result.add(temp);
System.out.println("Result is : " + result);
temp.remove(temp.size() - 1);
System.out.println("Temp is : " + result);
System.out.println("Result is : " + result);
temp.add(1, 3);
System.out.println("Temp is : " + temp);
result.add(new ArrayList<>(temp));
System.out.println("Result is : " + result);
}
輸出
Temp is : [1, 2]
Result is : [[1, 2]]
Temp is : [[1]]
Result is : [[1]]
Temp is : [1, 3]
Result is : [[1, 3], [1, 3]]