I see how to pass an ArrayList by its value so that the called method doesn't modify the original Arraylist. Passing ArrayList as value only and not reference However, I'm trying to pass an ArrayList that itself contains other Arraylists; that is Arraylist of Arraylist.
public class Test {
public static void main(String[] args){
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
for(int j=0;j<2;j++){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=5;i>0;i--){
list.add(i);
}
lists.add(list);
}
System.out.println("Before");
printLists(lists);
processLists(lists);
System.out.println("\nAfter");
printLists(lists);
}
public static void processLists(ArrayList<ArrayList<Integer>> list){
ArrayList<ArrayList<Integer>> myTrace=new ArrayList<ArrayList<Integer>>(list);
//myTrace.addAll(list);
for(int j=0;j<myTrace.size();j++){
myTrace.get(j).remove(myTrace.get(j).size()-1); //remove last element in the inner lists
}
System.out.println("\nInside");
printLists(myTrace);
}
public static void printLists(ArrayList<ArrayList<Integer>> lists){
for(int i=0;i<lists.size();i++){
for(int j=0;j<lists.get(i).size();j++){
System.out.print(lists.get(i).get(j)+" ");
}
System.out.println();
}
}
}
Suppose the above code generates output as:
Before: 5 4 3 2 1 \n 5 4 3 2 1
Inside: 5 4 3 2 \n 5 4 3 2
After: 5 4 3 2 \n 5 4 3 2
Here, processLists method is changing the original contents of 'lists'. How to restrict this modification? I've tried with the solutions mentioned in the link. Though it works with single ArrayList, but not with ArrayList of ArrayList.