Output is self explanatory.
Misconceptions
1.) temp.remove(temp.size() - 1);
This removes last element from temp list and since temp list is being referred inside result so it get referenced there as well.
2.) temp.add(1, 3);
It will add the value 3 at the index 1 in the temp list .
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);
}
output
Temp is : [1, 2]
Result is : [[1, 2]]
Temp is : [[1]]
Result is : [[1]]
Temp is : [1, 3]
Result is : [[1, 3], [1, 3]]