简体   繁体   中英

ArrayList inside an ArrayList in java

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]] [[]]

innerlist is pointing still pointing to the ArrayList.

Check this: What is the difference between a deep copy and a shallow copy?

This is happening because add doesn't copy anything - it just adds a reference to the object you pass as parameter to the end of the list. If you want that changes to the innerlist reference don't affect your list at all, you need to copy it, for example using the constructor taking a Collection parameter . You can do this either when adding

list.add(new ArrayList<>(innerlist));

or you reassign innerlist to a new list after adding

list.add(innerlist);
innerlist = new ArrayList<>();

especially if you need to clear it anyway at that point. See also this question , which handles the same problem, but without an outer list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM