-1
    ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();
    ArrayList<Integer> aList = new ArrayList<>();
    ArrayList<Integer> bList = new ArrayList<>();


    aList.add(1);
    treeList.add(aList);

    bList = treeList.remove(0);
    aList.clear();  //bList will be cleared

I know that bList and aList will refer to the same object,so when aList.clear(), bList will clear too, is there any way to make bList a new object.

Courage
  • 1
  • 2

3 Answers3

2

... is there any way to make bList a new object.

You can copy it; e.g.

bList = new ArrayList<>(treeList.remove(0)); 

See How to copy Java Collections list


Actually, this looks like a case that would benefit from writing your own custom classes.

As written, your treeList is an open data structure. Anything that has access to treeList or any of its component ArrayList objects can interfere with it. That's OK in some circumstances. But if you want to protect against having different parts of your codebase "mess up" the data structure then you should put the data structure behind an abstraction boundary; e.g.

public class MyThing {
    private ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();

    public void add(ArrayList<Integer> l){
        treeList.add(new ArrayList<>(l));
    }

    public void remove(int index) {
        return new ArrayList<>(treeList.remove(index));
    }
}

Notice that MyThing carefully copies the lists when it adds them and when it removes them so that one client of the MyThing API cannot interfere with another one via shared lists.

Obviously, there is a cost in doing this.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Try this. Pass the return of the remove as an argument to the ArrayList constructor.

ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();
ArrayList<Integer> aList = new ArrayList<>();
ArrayList<Integer> bList = new ArrayList<>();


aList.add(1);
treeList.add(aList);

bList =  new ArrayList<>(treeList.remove(0));
aList.clear();  //bList will be cleared
System.out.println(bList);

Prints

[1]
WJS
  • 36,363
  • 4
  • 24
  • 39
1

Alternatively, instead of assigning:

bList = treeList.remove(0);

you can use List#addAll

bList.addAll(treeList.remove(0));
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • 1
    Agreed. The problem we have is that the OP has not explained what they are really trying to do. Depending on what the real problem is, this could be a better solution. – Stephen C Jun 13 '20 at 01:52