I came across a problem in which I had to use nested ArrayList in java and had to clear the innerlist after each iteration. I noticed that when I added the innerlist to the main list and cleared the innerlist later , the value of the main list changed . Can anyone please explain why this is happening . Also , will there be any change if I use array instead of ArrayList. I have attached the code to my problem below to make it clear.
import java.util.*;
import java.lang.*;
import java.io.*;
class Example
{
public static void main(String []args){
ArrayList<ArrayList<Integer>> list= new ArrayList<>();
ArrayList<Integer> innerlist = new ArrayList<>();
innerlist.add(1);
list.add(innerlist);
System.out.println(list);
innerlist.clear();
System.out.println(list);
}
}
Output : [[1]] [[]]